

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: 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.
    """
    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)
    flashes = context.get('flash_alerts', 'None')
    ema5_long = context.get("ema5_long", "Not checked")
    ema5_short = context.get("ema5_short", "Not checked")
    
    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}

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

    if direction == "NEUTRAL":
        # v1.32.1: Inject macro context even in NEUTRAL fallback
        macro_note = ""
        if crude_trend != "unknown":
            macro_note = f" Macro: Crude is {crude_trend} ({crude_change:+.1f}%)."
        
        return (f"NEUTRAL — {contrib_str}. Spot {int(spot)}, PCR {pcr}, VIX {vix}.{macro_note} "
                f"No clear directional edge; wait for a breakout or a level shift.")

    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}.")

