#!/usr/bin/env python3
"""AI brain tools for Sailar-x.

  python brain_cli.py test [--search]   check your API keys, the models found, and one tiny call per provider
  python brain_cli.py research          fetch a fresh market brief now (Gemini + Google Search)
  python brain_cli.py report            is the AI actually helping? (needs some shadow-mode history)
  python brain_cli.py advise            ask the AI for parameter ideas to TEST in a backtest (it never changes anything)
  python brain_cli.py ask "question"    free question to the AI

Add  --config config.mt5.json  to use another config file.
"""
import argparse
import json
import sys
import time
import pandas as pd
from sailar import config
from sailar.brain import make_brain
from sailar.brain.llm import LLMError, parse_json
from sailar.journal import Journal
from sailar.metrics import summarize


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["test", "research", "report", "advise", "ask"])
    ap.add_argument("text", nargs="?")
    ap.add_argument("--config")
    ap.add_argument("--search", action="store_true")
    a = ap.parse_args()
    cfg = config.load(a.config)
    j = Journal(config.STATE / "journal.db")
    b = make_brain(cfg, j)

    if a.cmd == "test":
        print(f"Brain mode: {b.mode}")
        if not b.router.providers:
            sys.exit("No API keys found. Add GROQ_API_KEY and/or GEMINI_API_KEY to your .env file (see .env.example).")
        ok = True
        for name, p in b.router.providers.items():
            try:
                t0 = time.time()
                model = p.model(15)
                r = b.router.chat("Reply with JSON only.", 'Reply with exactly: {"ok": true}', prefer=name, timeout=20)
                good = parse_json(r.text).get("ok") is True
                print(f"PASS  {name}: model {model}, answered in {r.latency_ms} ms" if good else f"WARN  {name}: odd answer: {r.text[:80]}")
            except Exception as e:
                ok = False
                print(f"FAIL  {name}: {e}")
        if a.search:
            try:
                out = b.research.refresh()
                print(f"PASS  research ({out.get('provider', 'search')}): mood {out['mood']}, {len(out['events'])} events, {len(out['sources'])} sources")
            except Exception as e:
                ok = False
                print(f"FAIL  research: {e}")
        print("\nReady." if ok else "\nFix the FAIL lines above (a wrong or expired key is the usual cause).")
    elif a.cmd == "research":
        out = b.research.refresh()
        print(json.dumps({k: out[k] for k in ("mood", "bias", "summary", "events", "headlines")}, indent=2))
        print("\nSources:")
        for s in out.get("sources", []):
            print(" -", s["title"], s["uri"])
    elif a.cmd == "report":
        v = b.value()
        s = v.pop("_summary")
        print(f"Trades reviewed by the AI and since closed: {s['reviewed_trades']}")
        for k, g in v.items():
            print(f"  {k:8} trades {g['trades']:3}  win rate {g['win_rate']:.0%}  avg {g['avg_r']:+.2f}R  net {g['net']:+.2f}")
        print(f"\nIf every REJECT had been skipped: {s['money_saved_if_rejects_were_skipped']:+.2f} money saved")
        print("" if s["enough_data"] else "\nToo few trades (need 30+) to say whether the AI helps. Keep it in shadow mode longer.")
    elif a.cmd == "advise":
        row = j.active_version() or (j.all_versions() and j.version(j.all_versions()[-1]["version"]))
        if not row:
            sys.exit("No strategy has run yet.")
        stats = summarize(j.trades(row["version"], "closed"), row["start_equity"], j.equity_series(row["version"]))
        res = b.advise(stats, row["params"], row.get("backtest"))
        print(res["summary"], "\n")
        for s in res["suggestions"]:
            print(f"  {s['parameter']}: {s['change']}  ({s['reason']})")
        print("\nThese are ideas to TEST with a backtest. Nothing was changed.")
    elif a.cmd == "ask":
        q = a.text or sys.exit('Usage: python brain_cli.py ask "your question"')
        brief = (b.research.latest() or {}).get("summary", "none")
        r = b.router.chat("You are a careful forex market analyst. Be concise and honest about uncertainty.",
                          f"Latest market brief: {brief}\n\nQuestion: {q}", json_mode=False, timeout=40, max_tokens=700, prefer="gemini")
        print(r.text)


if __name__ == "__main__":
    try:
        main()
    except LLMError as e:
        sys.exit(f"AI error: {e}")
