"""Sweep parking presets — primary risk lever for v7.356."""
import json
import subprocess
import shutil
from pathlib import Path

BASE = "configs/experiments/return_max_long_v7.356_composed_gld_compound.json"
SWEEP_DIR = Path("configs/experiments/_tune_v7356_sweep")
SWEEP_DIR.mkdir(exist_ok=True)
SNAPSHOT = "midlarge-liquid-long-v1_bucketfix_full_audit_canonical_ftb_fix_v2"


def make_config(name: str, parking_preset: str) -> str:
    with open(BASE) as f:
        cfg = json.load(f)
    cfg["experiment_name"] = name
    cfg["overrides"]["risk"]["cash_parking_preset"] = parking_preset
    path = SWEEP_DIR / f"{name}.json"
    path.write_text(json.dumps(cfg, indent=2))
    return str(path)


def run_backtest(config_path: str) -> dict:
    cmd = ["python3", "-m", "apps.backtester.run", "--manifest", config_path,
           "--start", "2022-01-01", "--split", "all", "--initial-equity", "10000",
           "--snapshot-id", SNAPSHOT]
    cache = Path(f"data/parquet/{SNAPSHOT}/.runtime_cache")
    if cache.exists():
        shutil.rmtree(cache)
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
    tail = proc.stdout.split("\n")[-10:]
    run_id = return_pct = sqs_total = trades = None
    for line in tail:
        if "Run complete:" in line:
            run_id = line.split("Run complete:")[1].strip()
        elif "Total return:" in line:
            return_pct = float(line.split(":")[1].strip().rstrip("%"))
        elif "SQS:" in line:
            sqs_total = float(line.split("SQS:")[1].strip().split(" ")[0])
        elif "Trades:" in line:
            trades = int(line.split(":")[1].strip())
    mdd = sharpe = pf = None
    if run_id:
        m_path = Path(f"runs/{run_id}/metrics/metrics_summary.json")
        if m_path.exists():
            m = json.loads(m_path.read_text())
            mdd = m["max_drawdown_pct"]
            sharpe = m["sharpe_ratio"]
            pf = m["profit_factor"]
    return {"return": return_pct, "trades": trades, "mdd": mdd, "sharpe": sharpe, "pf": pf, "sqs": sqs_total, "run_id": run_id}


PARKING_PRESETS = [
    "qqqm_low_dd_tqqq_active_v2_gld_brake_v2",       # BASELINE (current)
    "qqqm_low_dd_tqqq_active_v2_gld_brake_v3",       # v3 brake (potentially better)
    "qqqm_low_dd_tqqq_active_v3_gld_brake_v2",       # v3 tqqq
    "qqqm_low_dd_tqqq_active_v2_gld_brake_v2_r07",   # 70% risk variant
    "qqqm_low_dd_tqqq_active_v2_gld_brake_v2_temp100", # temperature tweak
    "qqqm_low_dd_tqqq_active_v2_gld_brake_v2_vol026", # vol gate
    "qqqm_low_dd_tqqq_active_v2_gld",                # no brake
    "qqqm_low_dd_tqqq_active_v2",                    # bare
    "qqqm_low_dd_tqqq_active",                       # simpler
    "qqqm_low_dd_tqqq_conservative_gld_brake_v2",    # conservative
    "qqqm_low_dd_tqqq_calm",                         # calm
    "qqqm_low_dd_tqqq_calm_v2",                      # calm v2
    "qqqm_low_dd_tqqq_calm_v2_gld",                  # calm + gold
    "qqqm_low_dd_gld",                               # no tqqq, with gold
    "qqqm_low_dd_risk25",                            # risk gate
    "composite_v1",                                  # composite parking
    "composite_v2",
]


def main():
    baseline = {"return": 2236.1, "mdd": 14.50, "sharpe": 2.72, "pf": 4.38, "sqs": 87.1, "trades": 293}
    print(f"BASELINE: ret={baseline['return']}% MDD={baseline['mdd']}% Sharpe={baseline['sharpe']} SQS={baseline['sqs']} trades={baseline['trades']}")
    print("=" * 120)
    results = []
    for preset in PARKING_PRESETS:
        name = f"P_{preset[:50]}"
        path = make_config(name, preset)
        print(f"\n>>> {preset}")
        try:
            r = run_backtest(path)
            r["name"] = name
            r["preset"] = preset
            d_ret = (r["return"] or 0) - baseline["return"]
            d_mdd = (r["mdd"] or 0) - baseline["mdd"]
            d_sqs = (r["sqs"] or 0) - baseline["sqs"]
            print(f"    ret={r['return']:.0f}% (Δ{d_ret:+.0f}) MDD={r['mdd']:.2f}% (Δ{d_mdd:+.2f}) Sharpe={r['sharpe']:.2f} PF={r['pf']:.2f} SQS={r['sqs']:.1f} (Δ{d_sqs:+.1f}) trades={r['trades']}")
            results.append(r)
        except Exception as e:
            print(f"    FAILED: {e}")

    print("\n" + "=" * 120)
    print("SUMMARY (sorted by SQS, then return):")
    results.sort(key=lambda x: (x.get("sqs") or 0, x.get("return") or 0), reverse=True)
    print(f"{'preset':56s} {'return':>10s} {'MDD':>8s} {'Sharpe':>8s} {'PF':>6s} {'SQS':>7s} {'trades':>7s}")
    print(f"{'BASELINE':56s} {baseline['return']:>9.0f}% {baseline['mdd']:>7.2f}% {baseline['sharpe']:>8.2f} {baseline['pf']:>6.2f} {baseline['sqs']:>7.1f} {baseline['trades']:>7d}")
    for r in results:
        print(f"{r['preset']:56s} {r['return']:>9.0f}% {r['mdd']:>7.2f}% {r['sharpe']:>8.2f} {r['pf']:>6.2f} {r['sqs']:>7.1f} {r['trades']:>7d}")

    # Best by SQS that maintains return >= 70% of baseline
    qualified = [r for r in results if r.get("return", 0) >= baseline["return"] * 0.7]
    if qualified:
        best = max(qualified, key=lambda x: x.get("sqs") or 0)
        print(f"\nBEST (SQS-improving + ret≥70%): {best['preset']}")
        print(f"  ret={best['return']:.0f}% MDD={best['mdd']:.2f}% Sharpe={best['sharpe']:.2f} PF={best['pf']:.2f} SQS={best['sqs']:.1f}")


if __name__ == "__main__":
    main()
