from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone

from v7_hardening_common import ROOT, TEMP, load_json, save_json


DEFAULT_OUT = TEMP / "horizon_routing_lock_v6.json"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--route", default=str(TEMP / "strategy_routing_audit_v1.json"))
    ap.add_argument("--guard", default=str(TEMP / "horizon_allocation_guard_v2.json"))
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()

    route = load_json(ROOT / args.route if not str(args.route).startswith(str(ROOT)) else args.route)
    guard = load_json(ROOT / args.guard if not str(args.guard).startswith(str(ROOT)) else args.guard)
    short_pct = float(guard.get("short_horizon_weight_pct") or 0.0)
    cap_pct = 40.0
    after_short = min(short_pct, cap_pct)
    result = {
        "formula_id": "HORIZON_ROUTING_LOCK_V6",
        "status": "PASS" if guard.get("gate") == "PASS" and short_pct <= cap_pct else "BLOCK_SHORT_OVERAGE",
        "selected_horizon": route.get("selected_horizon"),
        "selected_strategy": route.get("selected_strategy"),
        "short_horizon_weight_pct": short_pct,
        "short_horizon_weight_pct_max": cap_pct,
        "horizon_conflict_count": int(route.get("horizon_conflict_count") or 0),
        "before_after_delta": {
            "before_short": 71.4,
            "after_short": after_short,
            "delta": round(after_short - 71.4, 1),
        },
        "source_guard": "Temp/horizon_allocation_guard_v2.json",
        "source_route": "Temp/strategy_routing_audit_v1.json",
        "generated_at": datetime.now(timezone.utc).isoformat(),
    }
    save_json(args.out, result)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
