#!/usr/bin/env python3
"""Sailar-x command line.

  python run.py check --config config.mt5.json                    test the MT5 connection
  python run.py backtest [--csv FILE | --days 60 | --synthetic]   test the strategy on history (train/unseen split)
  python run.py run [--config FILE]                                start the 24/7 agent (sim | demo | live per config.json)
  python run.py status                                             print the current status
  python run.py report                                             write today's report now
  python run.py gate                                               check the go-live gate for the active version
  python run.py dashboard [--port 8787]                            open the live dashboard
  python run.py kill | unkill                                      emergency stop switch
"""
import argparse
import json
import sys
from sailar import config
from sailar.risk import KILL_FILE


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["check", "backtest", "run", "status", "report", "gate", "dashboard", "kill", "unkill"])
    ap.add_argument("--config")
    ap.add_argument("--csv")
    ap.add_argument("--days", type=int, default=60)
    ap.add_argument("--synthetic", action="store_true")
    ap.add_argument("--port", type=int, default=8787)
    a = ap.parse_args()
    cfg = config.load(a.config)

    if a.cmd == "check":
        from sailar import mt5check
        sys.exit(0 if mt5check.run(cfg) else 1)
    elif a.cmd == "kill":
        KILL_FILE.write_text("stop")
        print("Kill switch ON. The agent closes its position and stops.")
    elif a.cmd == "unkill":
        KILL_FILE.unlink(missing_ok=True)
        print("Kill switch OFF.")
    elif a.cmd == "backtest":
        from sailar.backtest import split_backtest
        from sailar import data
        if a.synthetic:
            df = data.synthetic_candles()
            print("NOTE: synthetic data, only for checking the machinery. These numbers mean nothing about real markets.")
        elif a.csv:
            df = data.load_csv(a.csv)
        else:
            df = data.fetch_history(cfg, a.days)
        res, _ = split_backtest(df, cfg["strategy"], cfg)
        print(json.dumps(res, indent=2))
    elif a.cmd == "run":
        from sailar.runner import run
        run(cfg)
    elif a.cmd in ("status", "report", "gate"):
        from sailar.journal import Journal
        j = Journal(config.STATE / "journal.db")
        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. Start with: python run.py run")
        if a.cmd == "status":
            p = config.STATE / "status.json"
            print(p.read_text() if p.exists() else "{}")
        elif a.cmd == "report":
            from sailar.report import save_and_send
            print("Wrote", save_and_send(j, row["version"], cfg))
        else:
            from sailar.gate import evaluate, write_pass_file
            r = evaluate(j, row["version"], cfg)
            for c in r["checks"]:
                print(("PASS " if c["ok"] else "FAIL ") + c["name"] + ": " + c["detail"])
            f = write_pass_file(r)
            print("\nGATE PASSED. You may consider a SMALL live account (read README first)." if f else "\nGate not passed. Keep demo trading.")
    elif a.cmd == "dashboard":
        from sailar.dashboard import serve
        serve(a.port)


if __name__ == "__main__":
    main()
