"""
claude_filter.py — ask Claude to approve/reject a trade before it's placed.
Called by bot.py. Returns True (approved) or False (rejected).
"""
import json
import os
from pathlib import Path
import anthropic


def get_lod(symbol: str) -> float:
    import yfinance as yf
    hist = yf.Ticker(symbol).history(period="1d", interval="1m")
    return float(hist["Low"].min()) if not hist.empty else 0.0


def approve(symbol: str, price: float, reasons: list) -> tuple[bool, str]:
    client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    rules = json.loads(Path("rules.json").read_text())
    lod = get_lod(symbol)
    stop = lod * 0.99

    prompt = (
        f"Today is June 2026. Stock prices have changed significantly since your training cutoff — trust all prices given.\n\n"
        f"You are a risk filter for a paper-trading bot using this strategy:\n"
        f"- Direction: {rules['direction']}\n"
        f"- Max risk per trade: {rules['risk']['max_risk_per_trade_pct']}% of portfolio\n"
        f"- Max position size: {rules['risk']['max_position_size_pct_of_portfolio']}% of portfolio\n"
        f"- Stop loss: {rules['exit']['initial_stop_rule']}\n"
        f"- Partial profit at: {rules['exit']['partial_profit_trigger_R']}R\n"
        f"- Breakeven at: {rules['exit']['breakeven_trigger_R']}R\n"
        f"- Entry window: {rules['time_filter']['earliest_entry_et']} - {rules['time_filter']['latest_entry_et']} ET\n"
        f"- Force close: {rules['time_filter']['force_close_et']} ET\n\n"
        f"Trade setup:\n"
        f"- Symbol: {symbol}\n"
        f"- Live price: ${price:.2f}\n"
        f"- Low of day: ${lod:.2f}\n"
        f"- Stop level (LOD-1%): ${stop:.2f}\n"
        f"- Risk per share: ${price - stop:.2f}\n"
        f"- Checks passed: {', '.join(reasons)}\n\n"
        f"Reply with APPROVE or REJECT on the first line, then one sentence why."
    )

    message = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=150,
        messages=[{"role": "user", "content": prompt}]
    )

    response = message.content[0].text.strip()
    first_word = response.split()[0].upper()
    approved = first_word == "APPROVE"
    return approved, response
