"""
AkDevz AI Market Intelligence — Gemini AI Explainer & Research Synthesizer
Transforms structured quantitative market evidence into transparent explanations.
AI acts strictly as an evidence reasoner, never as a raw calculator or price source.
"""
import json
import httpx
from typing import Dict, Any, Optional
from python.config.settings import settings

class GeminiAnalyzer:
    def __init__(self, api_key: str = "", model: str = ""):
        self.api_key = api_key or settings.gemini_api_key
        self.model = model or settings.gemini_model or "gemini-2.5-flash"
        self.timeout = settings.gemini_timeout_sec

    def generate_report(self, evidence_package: Dict[str, Any]) -> Dict[str, Any]:
        """
        Synthesizes research report from validated evidence package.
        Falls back gracefully to deterministic quant narrative if API key is not configured.
        """
        symbol = evidence_package.get("symbol", "INDEX")
        decision = evidence_package.get("decision", "WAIT")
        regime = evidence_package.get("regime", "UNCERTAIN")
        bias = evidence_package.get("market_bias", "NEUTRAL")
        ltp = evidence_package.get("ltp", 0.0)
        vwap = evidence_package.get("vwap", 0.0)

        # If Gemini API key is configured, call Google AI Studio API
        if self.api_key and self.api_key != "your_google_gemini_api_key_here":
            try:
                ai_result = self._call_gemini_api(evidence_package)
                if ai_result:
                    return ai_result
            except Exception as e:
                # Log and proceed to deterministic synthesis
                pass

        # Deterministic Quant Synthesis (Fallback / Offline Mode)
        supporting = []
        contradicting = []

        if decision == "BUY_CE":
            supporting.append(f"Price ({ltp:.2f}) is sustaining above Session VWAP ({vwap:.2f}) with bullish momentum.")
            supporting.append(f"Market regime identified as {regime} with positive indicator confluence.")
            contradicting.append("Overhead call writing resistance could slow upward velocity.")
            why_wait = "Setup is triggered. Execute with defined stop-loss; do not chase if price moves beyond trigger."
            hinglish = f"Bhai, NIFTY/Asset VWAP ke upar strong hold kar raha hai ({ltp:.2f}). Bullish setup confirm hua hai. Proper stop loss laga kar hi risk lein."
        elif decision == "BUY_PE":
            supporting.append(f"Price ({ltp:.2f}) broke below Session VWAP ({vwap:.2f}) with negative momentum.")
            supporting.append(f"Market regime identified as {regime} with bearish indicator confluence.")
            contradicting.append("Nearby put writing base could act as interim demand zone.")
            why_wait = "Setup is triggered. Execute with defined stop-loss; do not chase if price falls too fast."
            hinglish = f"Market VWAP ke niche slide kar raha hai ({ltp:.2f}). Bearish setup triggered hai, par support level ka dhyan rakhein."
        elif decision == "NO_TRADE":
            contradicting.append(f"Market is in a {regime} state with high risk of false breakouts.")
            contradicting.append("Projected reward-to-risk does not overcome realistic brokerage and slippage costs.")
            why_wait = "Expected value is negative. Sitting on cash is a high-probability winning decision here."
            hinglish = "Market abhi bohot choppy/sideways hai. False breakout me premium erode hoga. Is waqt NO TRADE sabse best decision hai."
        else: # WAIT
            contradicting.append("Required confirmation candle has not closed, or indicators are in conflict.")
            why_wait = "Waiting for genuine confirmation. Premature entry exposes capital to false moves."
            hinglish = "Direction clear hone ka wait karein. Candle close hone se pehle entry lena risky ho sakta hai."

        exec_summary = (
            f"{symbol} is currently trading at {ltp:.2f} in a {regime} regime ({bias}). "
            f"The quantitative engine has rendered a decision of {decision}. "
            f"{why_wait}"
        )

        return {
            "decision": decision,
            "market_bias": bias,
            "regime": regime,
            "executive_summary": exec_summary,
            "hinglish_explanation": hinglish,
            "supporting_reasons": supporting,
            "contradicting_reasons": contradicting,
            "why_wait_or_avoid": why_wait,
            "what_must_happen_next": evidence_package.get("what_to_watch_next", "Wait for candle close confirmation."),
            "invalidation_condition": f"Violation of Session VWAP ({vwap:.2f}) or adverse regime shift.",
            "raw_ai_response": json.dumps({"mode": "deterministic_quant_synthesis"}),
            "model_name": "quant-rules-engine-v1",
        }

    def _call_gemini_api(self, evidence: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent?key={self.api_key}"

        prompt = (
            "You are the senior market analyst for AkDevz AI Market Intelligence.\n"
            "Analyze the following validated evidence package for an Indian stock or index.\n"
            "You must return ONLY a valid JSON object matching this schema:\n"
            "{\n"
            '  "executive_summary": "Concise plain-English institutional summary",\n'
            '  "hinglish_explanation": "Concise conversational Hindi-English explanation for an Indian trader",\n'
            '  "supporting_reasons": ["Point 1", "Point 2"],\n'
            '  "contradicting_reasons": ["Point 1", "Point 2"],\n'
            '  "why_wait_or_avoid": "Clear reason why patience or skipping is required if not high conviction",\n'
            '  "what_must_happen_next": "Specific price, volume, or VWAP event to monitor",\n'
            '  "invalidation_condition": "What proves this idea wrong"\n'
            "}\n\n"
            f"EVIDENCE PACKAGE:\n{json.dumps(evidence, indent=2)}\n"
        )

        payload = {
            "contents": [
                {
                    "parts": [{"text": prompt}]
                }
            ],
            "generationConfig": {
                "temperature": 0.2,
                "responseMimeType": "application/json"
            }
        }

        with httpx.Client(timeout=float(self.timeout)) as client:
            resp = client.post(url, json=payload)
            if resp.status_code == 200:
                data = resp.json()
                raw_text = data["candidates"][0]["content"]["parts"][0]["text"]
                parsed = json.loads(raw_text)

                return {
                    "decision": evidence.get("decision", "WAIT"),
                    "market_bias": evidence.get("market_bias", "NEUTRAL"),
                    "regime": evidence.get("regime", "UNCERTAIN"),
                    "executive_summary": parsed.get("executive_summary", ""),
                    "hinglish_explanation": parsed.get("hinglish_explanation", ""),
                    "supporting_reasons": parsed.get("supporting_reasons", []),
                    "contradicting_reasons": parsed.get("contradicting_reasons", []),
                    "why_wait_or_avoid": parsed.get("why_wait_or_avoid", ""),
                    "what_must_happen_next": parsed.get("what_must_happen_next", ""),
                    "invalidation_condition": parsed.get("invalidation_condition", ""),
                    "raw_ai_response": raw_text,
                    "model_name": self.model,
                }
        return None
