from __future__ import annotations

import argparse
import json
from datetime import date
from pathlib import Path
from typing import Any
import yaml


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_HISTORY = ROOT / "Temp" / "proposal_evaluation_history.json"
DEFAULT_OUT = ROOT / "Temp" / "evaluation_history_coverage_v1.json"
DEFAULT_POLICY = ROOT / "spec" / "strategy_execution_lock_policy.yaml"


def _load_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return payload if isinstance(payload, dict) else {}


def _load_policy(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    try:
        payload = yaml.safe_load(path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    root = payload.get("strategy_execution_lock_policy") if isinstance(payload, dict) else {}
    obj = root.get("outcome_eval_window_v1") if isinstance(root, dict) else {}
    return obj if isinstance(obj, dict) else {}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--history", default=str(DEFAULT_HISTORY))
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    ap.add_argument("--policy", default=str(DEFAULT_POLICY))
    args = ap.parse_args()

    hp = Path(args.history)
    op = Path(args.out)
    pp = Path(args.policy)
    if not hp.is_absolute():
        hp = ROOT / hp
    if not op.is_absolute():
        op = ROOT / op
    if not pp.is_absolute():
        pp = ROOT / pp

    h = _load_json(hp)
    pol = _load_policy(pp)
    required_days = int(pol.get("t20_min_days_required") or 28)
    records = h.get("records") if isinstance(h.get("records"), list) else []
    dates = sorted({str(r.get("proposal_date")) for r in records if isinstance(r, dict) and r.get("proposal_date")})
    min_date = dates[0] if dates else None
    max_date = dates[-1] if dates else None
    elapsed = 0
    if min_date and max_date:
        try:
            elapsed = max(0, (date.fromisoformat(max_date) - date.fromisoformat(min_date)).days)
        except Exception:
            elapsed = 0
    maturity_pct = round(min(100.0, (elapsed / float(max(1, required_days))) * 100.0), 2)
    shortage_days = max(0, required_days - elapsed)
    gate = "READY" if shortage_days == 0 else ("NEAR_READY" if shortage_days <= 5 else "NOT_READY")

    out = {
        "formula_id": "EVALUATION_HISTORY_COVERAGE_V1",
        "metrics": {
            "records_count": len(records),
            "history_min_date": min_date,
            "history_max_date": max_date,
            "elapsed_days_from_min": elapsed,
            "required_days_t20": required_days,
            "shortage_days_t20": shortage_days,
            "maturity_pct": maturity_pct,
        },
        "gate": gate,
        "policy_used": {
            "policy_path": str(pp),
            "required_days_t20": required_days,
        },
    }
    op.parent.mkdir(parents=True, exist_ok=True)
    op.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(out, ensure_ascii=False, indent=2))
    return 0


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