from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_OUT = ROOT / "Temp" / "root_cause_recovery_plan_v1.json"


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


def _f(v: Any, default: float = 0.0) -> float:
    try:
        return float(v)
    except Exception:
        return default


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

    out_path = Path(args.out)
    if not out_path.is_absolute():
        out_path = ROOT / out_path

    op = _load(ROOT / "Temp" / "operational_report.json")
    sh = _load(ROOT / "Temp" / "strategy_hardening_harness_v1.json")
    oq = _load(ROOT / "Temp" / "outcome_quality_score_v1.json")
    pi = _load(ROOT / "Temp" / "prediction_improvement_harness.json")
    di = _load(ROOT / "Temp" / "data_integrity_score_v1.json")
    rb = _load(ROOT / "Temp" / "rebound_sell_efficiency_v1.json")
    pf = _load(ROOT / "Temp" / "perf_recovery_harness_v1.json")
    eg = _load(ROOT / "Temp" / "engine_harness_gate_result.json")

    baseline = {
        "data_integrity_score": _f(di.get("score")),
        "outcome_quality_score": _f(oq.get("score")),
        "t20_pass_rate": _f((oq.get("metrics") or {}).get("t20_pass_rate")),
        "algorithm_guidance_proof_score": _f((sh.get("domain_scores") or {}).get("algorithm_guidance_proof")),
        "overall_hardening_score": _f((sh.get("meta_scores") or {}).get("overall_hardening_score")),
        "prediction_match_rate_pct": _f((pi.get("summary") or {}).get("match_rate_pct")),
        "rebound_efficiency_score": _f((rb.get("metrics") or {}).get("rebound_efficiency_score")),
        "value_damage_pct_avg": _f((rb.get("metrics") or {}).get("value_damage_pct_avg")),
        "execution_quality_gate": str((pf.get("metrics") or {}).get("execution_quality_gate") or ""),
        "late_chase_status": str((pf.get("metrics") or {}).get("late_chase_status") or ""),
        "engine_gate_status": str(eg.get("status") or ""),
        "json_validation_status": str((op.get("summary") or {}).get("json_validation_status") or ""),
    }

    failed_dimensions: list[str] = []
    if baseline["data_integrity_score"] < 100.0:
        failed_dimensions.append("data_integrity")
    if baseline["outcome_quality_score"] < 60.0:
        failed_dimensions.append("outcome_quality")
    if baseline["t20_pass_rate"] < 60.0:
        failed_dimensions.append("t20_pass_rate")
    if baseline["prediction_match_rate_pct"] < 60.0:
        failed_dimensions.append("prediction_match_rate")
    if baseline["value_damage_pct_avg"] > 10.0:
        failed_dimensions.append("cash_recovery_value_damage")
    if baseline["execution_quality_gate"] in {"FAIL", "WATCH_PENDING_SAMPLE"}:
        failed_dimensions.append("execution_quality")
    if baseline["algorithm_guidance_proof_score"] < 95.0:
        failed_dimensions.append("algorithm_guidance_proof")

    top_errors = (pi.get("top_errors") or []) if isinstance(pi.get("top_errors"), list) else []
    top_errors = [x for x in top_errors if isinstance(x, dict)][:10]

    result = {
        "formula_id": "ROOT_CAUSE_RECOVERY_PLAN_V1",
        "baseline_scores": baseline,
        "failed_dimensions": failed_dimensions,
        "top_error_categories": top_errors,
        "required_harness_actions": [
            "OPERATIONAL_OUTCOME_LOCK_V1",
            "SMART_CASH_RECOVERY_V5",
            "STRATEGY_HARDENING_HARNESS_V2",
            "DATA_INTEGRITY_100_LOCK_V2",
        ],
        "unlock_criteria": {
            "data_integrity_score": 100.0,
            "outcome_quality_score_min": 60.0,
            "t20_pass_rate_min": 60.0,
            "prediction_match_rate_pct_min": 60.0,
            "value_damage_pct_avg_max": 10.0,
            "algorithm_guidance_proof_min": 95.0,
        },
        "no_fake_100_statement": "PASS_100 is valid only when all lock criteria are numerically satisfied.",
    }

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


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