"""Everything an AI model says is UNTRUSTED. This module turns it into strict, clamped, harmless data."""
import pandas as pd

DECISIONS = ("APPROVE", "REDUCE", "REJECT")
EVENT_RISK = ("none", "low", "medium", "high")
CATEGORIES = ("trend_failure", "news_spike", "range_chop", "stop_too_tight", "spread_or_slippage",
              "bad_timing", "good_trade", "other")


def _num(x, lo, hi, default):
    try:
        x = float(x)
    except Exception:
        return default
    if x != x:
        return default
    return max(lo, min(hi, x))


def _strs(xs, n, width):
    if not isinstance(xs, list):
        return []
    return [str(x)[:width] for x in xs[:n] if x is not None]


def verdict(obj):
    obj = obj if isinstance(obj, dict) else {}
    d = str(obj.get("decision", "APPROVE")).upper().strip()
    if d not in DECISIONS:
        d = "APPROVE"
    mult = _num(obj.get("size_multiplier", 1.0), 0.25, 1.0, 1.0)   # the AI can NEVER make a trade bigger
    if d == "APPROVE":
        mult = 1.0
    er = str(obj.get("event_risk", "none")).lower().strip()
    return {"decision": d, "size_multiplier": round(mult, 2), "confidence": int(_num(obj.get("confidence", 50), 0, 100, 50)),
            "event_risk": er if er in EVENT_RISK else "none", "reasons": _strs(obj.get("reasons"), 3, 160),
            "risks": _strs(obj.get("risks"), 3, 160), "summary": str(obj.get("summary", ""))[:200]}


def brief(obj, now):
    obj = obj if isinstance(obj, dict) else {}
    events = []
    for e in (obj.get("events") or [])[:25]:
        if not isinstance(e, dict):
            continue
        try:
            t = pd.Timestamp(e.get("time_utc"))
            t = t.tz_localize("UTC") if t.tzinfo is None else t.tz_convert("UTC")
        except Exception:
            continue
        imp = str(e.get("impact", "low")).lower()
        events.append({"time_utc": str(t), "currency": str(e.get("currency", ""))[:4].upper(),
                       "title": str(e.get("title", ""))[:120], "impact": imp if imp in ("high", "medium", "low") else "low"})
    heads = [{"currency": str(h.get("currency", ""))[:4].upper(), "text": str(h.get("text", ""))[:200]}
             for h in (obj.get("headlines") or [])[:6] if isinstance(h, dict)]
    mood = str(obj.get("mood", "unclear")).lower()
    bias = obj.get("bias") if isinstance(obj.get("bias"), dict) else {}
    bias = {str(k)[:4].upper(): (str(v).lower() if str(v).lower() in ("bullish", "bearish", "neutral") else "neutral")
            for k, v in list(bias.items())[:4]}
    return {"as_of": str(now), "events": events, "headlines": heads,
            "mood": mood if mood in ("risk_on", "risk_off", "mixed", "unclear") else "unclear",
            "bias": bias, "summary": str(obj.get("summary", ""))[:500]}


def postmortem(obj):
    obj = obj if isinstance(obj, dict) else {}
    c = str(obj.get("category", "other")).lower()
    return {"category": c if c in CATEGORIES else "other", "lesson": str(obj.get("lesson", ""))[:300],
            "suggestion": str(obj.get("suggestion", ""))[:300]}


def advice(obj):
    obj = obj if isinstance(obj, dict) else {}
    items = []
    for it in (obj.get("suggestions") or [])[:5]:
        if isinstance(it, dict):
            items.append({"parameter": str(it.get("parameter", ""))[:40], "change": str(it.get("change", ""))[:80],
                          "reason": str(it.get("reason", ""))[:200]})
    return {"summary": str(obj.get("summary", ""))[:400], "suggestions": items}
