

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":
        return f"ATM Put Surge: +{int(data['delta']):,} COI at {int(data['strike']):,}. Aggressive put writing detected."
        
    if t_type == "atm_call_surge":
        return f"ATM Call Surge: +{int(data['delta']):,} COI at {int(data['strike']):,}. Aggressive call writing detected."

    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')
    
    prompt = f"""You are Dinks, an expert options trader. Multiple signals have aligned:
Direction: {direction}
Reasons: {contrib_str}
Spot: {spot}, PCR: {pcr}, VIX: {vix}, Support: {sup}, Resistance: {res}, OI bias: {oi}
Macro Context: Crude is {crude_trend} ({crude_change:+.2f}%).
Recent Live Alerts (Crucial): {flashes}

Write ONE crisp master sentence summarizing this setup with the reasons. 
If there is a major directional bias, mention the macro tailwind/headwind (like crude). 
If the Recent Live Alerts show massive institutional buildup (like 'CALL WRITERS SURGING' or 'PUT WRITERS SURGING' at a specific strike), you MUST mention this battle in your sentence.
End with a specific trade action (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}.")

