"""
AkDevz AI Market Intelligence — Groq AI Reasoning Engine
Powered by Groq's high-speed inference with openai/gpt-oss-120b.
Synthesizes professional quantitative evidence into beginner-friendly,
structured market intelligence and plain-language Hinglish trade blueprints.
"""
import json
import logging
from typing import Dict, Any, Optional

try:
    from groq import Groq
except ImportError:
    Groq = None

from python.config.settings import settings

logger = logging.getLogger(__name__)

class GroqAnalyzer:
    def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None):
        self.api_key = api_key or settings.groq_api_key
        self.model = model or settings.groq_model or "openai/gpt-oss-120b"
        self.client = Groq(api_key=self.api_key) if (self.api_key and Groq) else None

    def generate_report(self, evidence_package: Dict[str, Any]) -> Dict[str, Any]:
        """
        Submits normalized market data package to Groq GPT-OSS-120B and parses structured trade analysis.
        """
        symbol = evidence_package.get("symbol", "INDEX")
        ltp = evidence_package.get("ltp", 0.0)
        vwap = evidence_package.get("vwap", 0.0)
        regime = evidence_package.get("regime", "UNKNOWN")
        quant_decision = evidence_package.get("decision", "WAIT")
        setup_name = evidence_package.get("setup_name", "NONE")
        rsi = evidence_package.get("rsi", 50.0)
        adx = evidence_package.get("adx", 20.0)
        atr = evidence_package.get("atr", 0.0)
        rvol = evidence_package.get("rvol", 1.0)
        squeeze = evidence_package.get("squeeze_state", "NORMAL")

        prompt = f"""
You are the Lead Derivatives Analyst and AI Trading Copilot at AkDevz AI Market Intelligence.
You act like a seasoned professional Indian market trader who explains complex market conditions
so clearly that even a beginner can trade safely without getting trapped.

EVIDENCE PACKAGE:
- Instrument: {symbol}
- Current LTP: {ltp}
- Session VWAP: {vwap}
- Market Regime: {regime}
- Quantitative Gate Decision: {quant_decision}
- Matched Strategy Setup: {setup_name}
- Technical Metrics: RSI(14)={rsi}, ADX={adx}, ATR={atr}, RVOL={rvol}, Squeeze={squeeze}

STRICT INSTRUCTIONS:
1. Ground your reasoning strictly on the evidence above. Never hallucinate prices.
2. Return ONLY a valid JSON object with the exact keys below.
3. Make the 'hinglish_explanation' extremely practical and friendly for Indian retail traders.
4. Give crisp, professional, capital-preservation advice.

JSON FORMAT REQUIRED:
{{
  "decision": "{quant_decision}",
  "market_bias": "BULLISH or BEARISH or NEUTRAL or UNCERTAIN",
  "regime": "{regime}",
  "executive_summary": "Clear 2-3 sentence overview of what is happening in {symbol}.",
  "hinglish_explanation": "Simple Hinglish explanation: Market ka mood kya hai, beginner ko kya karna chahiye, aur kahan trap lag sakta hai.",
  "supporting_reasons": ["Point 1 based on real data", "Point 2"],
  "contradicting_reasons": ["Risk factor 1", "Risk factor 2"],
  "why_wait_or_avoid": "Specific mathematical reason why patience/waiting is safer if no trigger exists.",
  "what_must_happen_next": "Exact price action or candle close condition required next.",
  "invalidation_condition": "Exact level that proves the setup completely wrong.",
  "beginner_copilot": {{
    "should_i_trade": "YES / WAIT / AVOID",
    "recommended_action": "e.g. Wait for 5m candle close above {ltp} or Avoid CE due to VWAP resistance",
    "target_strike": "e.g. ATM CE / PE or None",
    "risk_management_rule": "Do not risk more than 1.5% of total capital per trade."
  }},
  "model_name": "{self.model}"
}}
"""
        if not self.client:
            return self._fallback_quant_report(evidence_package)

        try:
            completion = self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "You are a professional quantitative Indian equity and derivatives market intelligence analyst. Return valid JSON only."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.7,
                max_completion_tokens=2048,
                top_p=0.9,
                reasoning_effort="medium",
                stream=False
            )

            response_text = completion.choices[0].message.content or "{}"
            
            # Clean markdown codeblocks if returned
            clean_text = response_text.strip()
            if clean_text.startswith("```json"):
                clean_text = clean_text[7:]
            if clean_text.startswith("```"):
                clean_text = clean_text[3:]
            if clean_text.endswith("```"):
                clean_text = clean_text[:-3]
            clean_text = clean_text.strip()

            parsed = json.loads(clean_text)
            parsed["model_name"] = f"groq/{self.model}"
            return parsed

        except Exception as e:
            logger.warning(f"Groq reasoning error ({str(e)}), falling back to deterministic synthesis.")
            return self._fallback_quant_report(evidence_package, error=str(e))

    def _fallback_quant_report(self, evidence: Dict[str, Any], error: Optional[str] = None) -> Dict[str, Any]:
        """Deterministic safety fallback if API is unreachable."""
        symbol = evidence.get("symbol", "NSE:NIFTY50-INDEX")
        ltp = evidence.get("ltp", 0.0)
        vwap = evidence.get("vwap", 0.0)
        decision = evidence.get("decision", "WAIT")
        regime = evidence.get("regime", "UNKNOWN")

        return {
            "decision": decision,
            "market_bias": "BULLISH" if ltp > vwap else "BEARISH",
            "regime": regime,
            "executive_summary": f"{symbol} is trading at {ltp:.2f} relative to Session VWAP ({vwap:.2f}) under {regime} regime. Decision Gate status is {decision}.",
            "hinglish_explanation": f"Market abhi {regime} mode me hai. Agar aap beginner hain, to jab tak confirmed trigger na mile tab tak jump mat kijiye. Capital bachana sabse pehla rule hai.",
            "supporting_reasons": [
                f"Price position relative to VWAP: {'Above' if ltp > vwap else 'Below'}",
                f"Market regime classified as {regime}"
            ],
            "contradicting_reasons": [
                "Intraday confirmation trigger pending confirmed candle close."
            ],
            "why_wait_or_avoid": "Waiting for objective setup confluence. Capital preservation takes precedence.",
            "what_must_happen_next": f"Monitor reaction around {vwap:.2f} and wait for volume expansion.",
            "invalidation_condition": f"Violation of Session VWAP ({vwap:.2f}).",
            "beginner_copilot": {
                "should_i_trade": "WAIT",
                "recommended_action": "Wait for confirmed 5-minute candle close before making any trade entry.",
                "target_strike": "ATM Contract",
                "risk_management_rule": "Never risk more than 1.5% of total capital."
            },
            "model_name": "groq-deterministic-quant-v1"
        }
