from __future__ import annotations

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


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_V1 = ROOT / "Temp" / "strategy_hardening_harness_v1.json"
DEFAULT_OUTCOME_LOCK = ROOT / "Temp" / "operational_outcome_lock_v1.json"
DEFAULT_DQ_LOCK = ROOT / "Temp" / "data_integrity_100_lock_v2.json"
DEFAULT_SCR_V4 = ROOT / "Temp" / "smart_cash_recovery_v4.json"
DEFAULT_SCR_V5 = ROOT / "Temp" / "smart_cash_recovery_v5.json"
DEFAULT_ENGINE_GATE = ROOT / "Temp" / "engine_harness_gate_result.json"
DEFAULT_PRED = ROOT / "Temp" / "prediction_accuracy_harness_v2.json"
DEFAULT_OAC_V2 = ROOT / "Temp" / "operational_alpha_calibration_v2.json"
DEFAULT_FIR_V1 = ROOT / "Temp" / "formula_runtime_registry_v1.json"
DEFAULT_DQR_V1 = ROOT / "Temp" / "data_quality_reconciliation_v1.json"
DEFAULT_OUT = ROOT / "Temp" / "strategy_hardening_harness_v2.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("--v1", default=str(DEFAULT_V1))
    ap.add_argument("--outcome-lock", default=str(DEFAULT_OUTCOME_LOCK))
    ap.add_argument("--dq-lock", default=str(DEFAULT_DQ_LOCK))
    ap.add_argument("--scr-v4", default=str(DEFAULT_SCR_V4))
    ap.add_argument("--scr-v5", default=str(DEFAULT_SCR_V5))
    ap.add_argument("--engine-gate", default=str(DEFAULT_ENGINE_GATE))
    ap.add_argument("--prediction", default=str(DEFAULT_PRED))
    ap.add_argument("--alpha-calibration", default=str(DEFAULT_OAC_V2))
    ap.add_argument("--formula-runtime", default=str(DEFAULT_FIR_V1))
    ap.add_argument("--data-quality-recon", default=str(DEFAULT_DQR_V1))
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()

    v1 = Path(args.v1)
    ol = Path(args.outcome_lock)
    dl = Path(args.dq_lock)
    sv = Path(args.scr_v4)
    sv5 = Path(args.scr_v5)
    eg = Path(args.engine_gate)
    pi = Path(args.prediction)
    op = Path(args.out)
    for p in (v1, ol, dl, sv, sv5, eg, pi, op):
        if not p.is_absolute():
            p = ROOT / p

    base = _load(ROOT / Path(args.v1) if not Path(args.v1).is_absolute() else Path(args.v1))
    outcome_lock = _load(ROOT / Path(args.outcome_lock) if not Path(args.outcome_lock).is_absolute() else Path(args.outcome_lock))
    dq_lock = _load(ROOT / Path(args.dq_lock) if not Path(args.dq_lock).is_absolute() else Path(args.dq_lock))
    scr_v4 = _load(ROOT / Path(args.scr_v4) if not Path(args.scr_v4).is_absolute() else Path(args.scr_v4))
    scr_v5 = _load(ROOT / Path(args.scr_v5) if not Path(args.scr_v5).is_absolute() else Path(args.scr_v5))
    engine = _load(ROOT / Path(args.engine_gate) if not Path(args.engine_gate).is_absolute() else Path(args.engine_gate))
    pred = _load(ROOT / Path(args.prediction) if not Path(args.prediction).is_absolute() else Path(args.prediction))
    oac = _load(ROOT / Path(args.alpha_calibration) if not Path(args.alpha_calibration).is_absolute() else Path(args.alpha_calibration))
    fir = _load(ROOT / Path(args.formula_runtime) if not Path(args.formula_runtime).is_absolute() else Path(args.formula_runtime))
    dqr = _load(ROOT / Path(args.data_quality_recon) if not Path(args.data_quality_recon).is_absolute() else Path(args.data_quality_recon))
    scr_current = scr_v5 if scr_v5 else scr_v4

    ds = base.get("domain_scores") if isinstance(base.get("domain_scores"), dict) else {}
    ms = base.get("meta_scores") if isinstance(base.get("meta_scores"), dict) else {}

    data_integrity = _f(ds.get("data_integrity"))
    outcome_quality = _f(ds.get("outcome_quality"))
    t20_pass = _f(ds.get("t20_pass_rate"))
    algo_proof = _f(ds.get("algorithm_guidance_proof"))
    pred_summary = pred.get("summary") if isinstance(pred.get("summary"), dict) else {}
    pred_match = _f(
        pred_summary.get("match_rate_pct")
        if pred_summary
        else pred.get("t5_ap_combined")
        if pred.get("t5_ap_combined") is not None
        else pred.get("t20_replay_rate")
    )
    if pred_match <= 0.0:
        pred_match = _f(pred.get("t5_ap_combined"), _f(pred.get("t20_replay_rate")))
    value_damage = _f(scr_current.get("value_damage_pct_avg"))
    expect = _f((outcome_lock.get("metrics") or {}).get("execution_expectancy_pct"))
    win_rate = _f((outcome_lock.get("metrics") or {}).get("execution_win_rate_pct"))
    t20_oper_count = _f((outcome_lock.get("metrics") or {}).get("operational_t20_count"))
    t20_oper_pass = _f((outcome_lock.get("metrics") or {}).get("operational_t20_pass_rate"))
    oac_conf = _f(oac.get("confidence_score"))
    oac_gate = str(oac.get("gate") or "MISSING")
    runtime_coverage = _f(fir.get("runtime_adjusted_coverage_pct"))
    dq_conflict = bool(dqr.get("quality_conflict_flag"))
    dq_invest = _f(dqr.get("investment_quality_score"))
    dq_cap_basis = _f(dqr.get("confidence_cap_basis_score"), dq_invest)

    readiness_reasons: list[str] = []
    if str(dq_lock.get("gate") or "") != "PASS_100":
        readiness_reasons.append("DATA_INTEGRITY_LOCK_NOT_PASS_100")
    if outcome_quality < 60.0:
        readiness_reasons.append("OUTCOME_QUALITY_LT_60")
    if t20_oper_count < 30:
        readiness_reasons.append("OPERATIONAL_T20_SAMPLE_LT_30")
    if t20_oper_pass < 60.0:
        readiness_reasons.append("OPERATIONAL_T20_PASS_LT_60")
    if expect <= 0.1:
        readiness_reasons.append("EXPECTANCY_LE_0_1")
    if win_rate < 45.0:
        readiness_reasons.append("WIN_RATE_LT_45")
    if pred_match < 60.0:
        readiness_reasons.append("PREDICTION_MATCH_LT_60")
    if value_damage > 10.0:
        readiness_reasons.append("VALUE_DAMAGE_GT_10")
    if str(engine.get("status") or "") != "OK":
        readiness_reasons.append("ENGINE_GATE_NOT_OK")
    if oac_gate not in {"PERFORMANCE_READY", "NOT_READY"}:
        readiness_reasons.append("ALPHA_CALIBRATION_MISSING")
    if runtime_coverage < 100.0:
        readiness_reasons.append("RUNTIME_COVERAGE_LT_100")
    if dq_conflict:
        readiness_reasons.append("DATA_QUALITY_CONFLICT")
    if dq_cap_basis < 50.0:
        readiness_reasons.append("DATA_QUALITY_CAP_BASIS_LT_50")

    readiness_gate = "PERFORMANCE_READY" if not readiness_reasons else "NOT_PERFORMANCE_READY"
    if "OPERATIONAL_T20_SAMPLE_LT_30" in readiness_reasons:
        readiness_gate = "WATCH_PENDING_SAMPLE"

    control = _f(ms.get("control_score"))
    perf_v1 = _f(ms.get("performance_score"))
    lock_boost = 100.0 if str(outcome_lock.get("unlock_state") or "") == "PERFORMANCE_READY" else 50.0
    perf_v2 = round((perf_v1 * 0.5) + (t20_oper_pass * 0.2) + (pred_match * 0.15) + (max(0.0, 100.0 - value_damage * 5.0) * 0.15), 2)
    overall = round(control * 0.55 + perf_v2 * 0.45, 2)
    truth_hardening_score = round(min(overall, max(0.0, dq_cap_basis), max(0.0, 100.0 - max(0.0, value_damage - 10.0) * 10.0)), 2)

    result = {
        "formula_id": "STRATEGY_HARDENING_HARNESS_V2",
        "domain_scores": {
            **ds,
            "prediction_match_rate_pct": pred_match,
            "cash_recovery_value_damage_pct": value_damage,
            "operational_t20_count": t20_oper_count,
            "operational_t20_pass_rate": t20_oper_pass,
            "execution_expectancy_pct_operational": expect,
            "execution_win_rate_pct_operational": win_rate,
            "alpha_calibration_confidence_score": oac_conf,
            "formula_runtime_coverage_pct": runtime_coverage,
            "data_quality_investment_score": dq_invest,
            "data_quality_cap_basis_score": dq_cap_basis,
            "data_quality_conflict_flag": dq_conflict,
            "algorithm_guidance_proof": algo_proof,
            "t20_pass_rate": t20_pass,
            "data_integrity": data_integrity,
            "outcome_quality": outcome_quality,
        },
        "meta_scores": {
            "control_score": control,
            "performance_score_v1": perf_v1,
            "performance_score_v2": perf_v2,
            "lock_score": lock_boost,
            "overall_hardening_score": overall,
            "truth_hardening_score": truth_hardening_score,
            "readiness_gate": readiness_gate,
            "readiness_reasons": readiness_reasons,
            "alpha_calibration_gate": oac_gate,
        },
        "targets": {
            "data_integrity_score": 100.0,
            "outcome_quality_min": 60.0,
            "operational_t20_sample_min": 30,
            "operational_t20_pass_min": 60.0,
            "execution_expectancy_pct_min": 0.1,
            "execution_win_rate_pct_min": 45.0,
            "prediction_match_rate_pct_min": 60.0,
            "value_damage_pct_avg_max": 10.0,
            "engine_gate_status": "OK",
            "formula_runtime_coverage_pct": 100.0,
            "data_quality_conflict_flag": False,
        },
    }

    out_path = ROOT / Path(args.out) if not Path(args.out).is_absolute() else Path(args.out)
    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())
