

import os
from dotenv import load_dotenv
load_dotenv('/home/dinkstrade/pdmp/.env', override=True)
from groq import Groq

def ask_groq(prompt):
    try:
        api_key = os.getenv("GROQ_API_KEY", "")
        if not api_key:
            print("[Groq] No API key")
            return None
        client = Groq(api_key=api_key)
        
        # v2.1: Simplified call — no reasoning_effort, plain messages
        chat = client.chat.completions.create(
            messages=[
                {"role": "user", "content": prompt}
            ],
            model="openai/gpt-oss-120b",
            temperature=0.3,
            max_tokens=2000
        )
        content = chat.choices[0].message.content
        if content and content.strip():
            return content.strip()
        else:
            print(f"[Groq] Empty response. Finish reason: {chat.choices[0].finish_reason}")
            return None
    except Exception as e:
        print(f"[Groq Error] {type(e).__name__}: {e}")
        return None
        client = Groq(api_key=api_key)
        chat = client.chat.completions.create(
            messages=[
                {"role": "system", "content": "You are a direct trading assistant. Respond only with the requested single sentence. No reasoning, no preamble, no markdown."},
                {"role": "user", "content": prompt}
            ],
            model="openai/gpt-oss-120b",
            temperature=0.3,
            max_tokens=1000
        )
        return chat.choices[0].message.content.strip()
    except Exception as e:
        print(f"[Groq Error] {e}")
        return None

def build_sentence(trigger, context, spot):
    t_type = trigger['type']
    data = trigger['data']

    # Build the prompt
    prompt = f"""You are Dinks, an expert options trader genie. Write exactly ONE sentence explaining this trigger and action.
Trigger: {t_type}
Data: {data}
Context: Spot={spot}, PCR={context.get('pcr')}, VIX={context.get('vix')}, Support={context.get('support')}, Resistance={context.get('resistance')}, VWAP={context.get('vwap')}, OI Bias={context.get('oi_bias')}, MTF_Resistance={context.get('mtf_resistance')}, MTF_Support={context.get('mtf_support')}, Shadow_Spot={context.get('shadow_spot')}, Shadow_CE_{context.get('shadow_ce_strike')}={context.get('shadow_ce')}, Shadow_PE_{context.get('shadow_pe_strike')}={context.get('shadow_pe')}
Rules: Be direct, use the numbers, mention the strike. End with a trade action (e.g. Over X: long, target Y, stop Z)."""

    ai_sentence = ask_groq(prompt)
    if ai_sentence:
        return ai_sentence

    # Fallback to hardcoded strings if Groq fails

    t_type = trigger['type']
    data = trigger['data']

    pcr = context.get('pcr') or 1.0
    vix = context.get('vix') or 15.0

    if t_type == "support_conviction_cross":
        strike = int(data.get('strike') or spot)
        tier = data['strike_tier']
        score = data['score']
        jumped_from = data.get('jumped_from')
        jump_txt = f" (jumped from {jumped_from:.0f}%)" if jumped_from is not None else ""
        action = f"Bias BULLISH while this holds. Over {int(spot)}: long, target {int(spot+100)}, stop {int(spot-50)}."
        return (f"Support at {strike:,} hardened — conviction crossed {tier}% "
                f"to {score:.0f}%{jump_txt}. PCR {pcr:.2f}, VIX {vix:.1f}. {action}")

    if t_type == "resistance_conviction_cross":
        strike = int(data.get('strike') or spot)
        tier = data['strike_tier']
        score = data['score']
        jumped_from = data.get('jumped_from')
        jump_txt = f" (jumped from {jumped_from:.0f}%)" if jumped_from is not None else ""
        action = f"Bias BEARISH while this holds. Under {int(spot)}: short, target {int(spot-100)}, stop {int(spot+50)}."
        return (f"Resistance at {strike:,} hardened — conviction crossed {tier}% "
                f"to {score:.0f}%{jump_txt}. PCR {pcr:.2f}, VIX {vix:.1f}. {action}")

    if t_type == "support_conviction_fade":
        strike = int(data.get('strike') or spot)
        return (f"Support at {strike:,} weakening — conviction dropped from "
                f"{data['from']:.0f}% to {data['to']:.0f}% (-{data['drop']:.0f}). "
                f"Watch for a break; PCR {pcr:.2f}, VIX {vix:.1f}.")

    if t_type == "resistance_conviction_fade":
        strike = int(data.get('strike') or spot)
        return (f"Resistance at {strike:,} weakening — conviction dropped from "
                f"{data['from']:.0f}% to {data['to']:.0f}% (-{data['drop']:.0f}). "
                f"Breakout setup forming; PCR {pcr:.2f}, VIX {vix:.1f}.")

    if t_type == "support_shift":
        return (f"Support shifted from {int(data['old']):,} to {int(data['new']):,}. "
                f"Adjust stops and targets. PCR {pcr:.2f}.")

    if t_type == "resistance_shift":
        return (f"Resistance shifted from {int(data['old']):,} to {int(data['new']):,}. "
                f"Adjust targets. PCR {pcr:.2f}.")

    if t_type == "orb_breakout_up":
        return (f"ORB breakout UP over {int(data['level']):,} "
                f"(close {data.get('close', 0):.1f}). Momentum bullish. PCR {pcr:.2f}.")

    if t_type == "orb_breakout_down":
        return (f"ORB breakout DOWN under {int(data['level']):,} "
                f"(close {data.get('close', 0):.1f}). Momentum bearish. PCR {pcr:.2f}.")

    if t_type == "oi_bias_flip":
        return (f"OI Bias flipped {data['old']} -> {data['new']}. "
                f"Writers changed sides; recheck directional bias.")

    if t_type == "oi_surge":
        return (f"OI Surge of {int(data['delta']):,} net bias score. "
                f"Heavy writer accumulation — watch for directional move.")
                
    if t_type == "call_wall_shift":
        return f"Call wall shifted from {int(data['old']):,} to {int(data['new']):,}. Resistance has moved."
        
    if t_type == "put_wall_shift":
        return f"Put wall shifted from {int(data['old']):,} to {int(data['new']):,}. Support has moved."
        
    if t_type == "atm_put_surge":
        # Convert raw COI to Lakhs (e.g., 4246905 -> 42.4 Lakh)
        lakhs = data['delta'] / 100000
        return f"Support at {int(data['strike']):,} hardened with +{lakhs:.1f} Lakh new put writers in the last 15 minutes."
        
    if t_type == "atm_call_surge":
        lakhs = data['delta'] / 100000
        return f"Resistance at {int(data['strike']):,} hardened with +{lakhs:.1f} Lakh new call writers in the last 15 minutes."

    return f"{t_type} detected."


def build_master_sentence(direction, contributing, context, spot, target, stop, stand_aside_reason=None):
    """
    v1.31.0 — Consolidated one-sentence verdict.
    If stand_aside_reason is provided, speaks the stand-aside sentence instead of a trade call.
    """
    # v1.36.6: If trade engine blocked the trade (target == spot), we do NOT return hardcoded.
    # We pass a flag to the LLM so it can contextualize the block (e.g., "dead in the water").
    trade_blocked = (target == spot or stop == spot)

    contrib_str = " + ".join([t.replace("_", " ") for t in contributing])
    pcr = context.get('pcr')
    vix = context.get('vix')
    sup = context.get('support')
    res = context.get('resistance')
    oi = context.get('oi_bias')

    if stand_aside_reason:
        bias_word = "bullish" if direction == "BULLISH" else ("bearish" if direction == "BEARISH" else "neutral")
        return (f"STAY OUT — The bias is {bias_word} ({contrib_str}), "
                f"but do not take this trade. Stand aside. {stand_aside_reason}")

    crude_trend = context.get('crude_trend', 'unknown')
    crude_change = context.get('crude_change', 0.0)
    crude_note = f"Crude is {crude_trend} ({crude_change:+.2f}%)" if abs(crude_change) >= 1.5 else "Crude is flat/irrelevant"

    flashes = context.get('flash_alerts', 'None')
    ema5_long = context.get("ema5_long", "Not checked")
    ema5_short = context.get("ema5_short", "Not checked")
    
    hw_moves = context.get('heavyweight_moves', {})
    hw_str = ', '.join([f'{k} {v:+.2f}%' for k, v in hw_moves.items()]) if hw_moves else 'N/A'
    overnight_gap = context.get('overnight_gap_pct', 0.0)
    gap_note = f'Overnight Gap: {overnight_gap:+.2f}%' if abs(overnight_gap) > 0.1 else 'No gap'

    support_oi = context.get('support_oi_total', 0)
    resistance_oi = context.get('resistance_oi_total', 0)
    max_pain = context.get('max_pain', 0)
    
    # Format the OI numbers nicely (e.g., 3.03 Crore)
    sup_oi_str = f"{support_oi / 10000000:.2f} Crore" if support_oi else "unknown"
    res_oi_str = f"{resistance_oi / 10000000:.2f} Crore" if resistance_oi else "unknown"

    prompt = f"""You are Dinks, an expert options trader. 
Current Market Structure:
- Spot: {spot}
- PCR: {pcr}, VIX: {vix}
- Support Floor: {sup} (Total Put OI: {sup_oi_str})
- Resistance Ceiling: {res} (Total Call OI: {res_oi_str})
- Max Pain: {max_pain}
- Direction Bias: {direction}
- Reasons: {contrib_str}
- Macro: Crude is {crude_trend} ({crude_change:+.2f}%)
- 30m EMA5 Long: {ema5_long}
- 30m EMA5 Short: {ema5_short}
- Recent Alerts: {flashes}
- Nearby MTF Zones: {context.get('nearby_zones', 'None')}
- Heavyweight Momentum: {hw_str}
- Overnight Gap: {gap_note}
- Close Momentum: {context.get('close_momentum', {})}

ZONE RULE: If Spot is inside or near a zone listed in "Nearby MTF Zones", you MUST mention it. If Spot is near a BEAR zone (above), warn: "Spot is at [TF] Bear Zone [bottom-top]. Watch for rejection or breakout." If Spot is near a BULL zone (below), say: "Spot is near [TF] Bull Zone [bottom-top]. Watch for bounce."

GAP RULE: If Overnight Gap is > +0.5%, explicitly state the market opened with a GAP UP. If < -0.5%, state GAP DOWN. If yesterday was a holiday, note that the gap reflects 2 days of macro moves.
HEAVYWEIGHT RULE (NON-NEGOTIABLE): You MUST mention the heavyweight moves ({hw_str}) in the FIRST sentence of your narrative. Even if they are small, the reader needs to know which stocks are driving the index. If HDFC Bank or Reliance is up > 1%, it is a primary driver of the gap up. If they are down, it is a drag.
LATE CLOSE RULE (HIGHEST PRIORITY): If Close Momentum price_delta > +100 and oi_drop > 0, the FIRST SENTENCE of your narrative MUST state that a violent short squeeze occurred into the close (include the exact price delta and OI drop). You MUST warn that a gap-up is highly probable due to this squeeze. You may THEN mention that aggressive selling (fade) is possible if fresh Call writers step in at the open. This rule overrides all macro/news bearishness. If price_delta < -100, state it was aggressive selling into the close, implying a gap-down risk.

SPOT RULES:
1. If Price is above the 5 EMA and 20 EMA, the trend is strong. Say "Price is riding the 5 EMA, trend is intact."
2. If Price is between the 200 EMA High and Low (200 EMA value +/- 15 pts), say "Price is at the 200 EMA band. Institutional floor/ceiling. Watch for a hard bounce."
3. If Price pulls back to the 50% Gap Fill level, warn: "Price is testing the 50% Gap Fill. Key support."
4. If Price hits today's High or Low, warn of a possible reversal.

CRITICAL RULE: If the 'Recent Alerts' shows 'None' (meaning no premium breakouts) and both Support and Resistance convictions are >80%, you MUST start the sentence with: "The market is dead in the water. There is no momentum. Do not trade. Wait for the London open or a premium spike."

Write a short, punchy narrative (2-3 sentences) explaining exactly where the market is trapped. 
Use the exact numbers. Explain that the market is stuck between the Put Wall (floor) and the Call Wall (ceiling). 
Mention where Spot is sitting relative to these walls.
If the 30m EMA5 shows "Touched 5 EMA and riding up", mention this as technical confirmation.
If the bias is RANGE-LOCKED, explicitly say "The market is stuck."
Conclude with an actionable takeaway: Either "Stand aside" or "Wait for a breakout" or give a specific trade (target {target}, stop {stop})."""

    ai_sentence = ask_groq(prompt)
    if ai_sentence:
        return ai_sentence

    bias = "Long" if direction == "BULLISH" else "Short"
    return (f"{direction} — {contrib_str}. Spot {int(spot)}, PCR {pcr}, VIX {vix}. "
            f"{bias}: target {target}, stop {stop}.")

