"""run_engine_audit_golden_cases_v1.py — IMPUTED_DATA_EXPOSURE_GATE_V1 Golden Sample Test

알려진 입력(domain coverage 조합) → 알려진 출력(gate_status / imputed_field_ratio /
effective_confidence_honest / long_horizon_allowed / fundamental_claim_allowed)을
결정론적으로 검증한다.

종료코드: 실패 케이스가 있으면 1.
"""
from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tools"))

# 산식 상수 (build_engine_audit_v1.py와 동기)
BLOCK_RATIO = 0.50
WARN_RATIO = 0.25
FUND_FACTOR_MIN_COVERAGE = 0.50
DOMAIN_WEIGHTS = {
    "fundamental_core": 0.30,
    "realized_outcome": 0.30,
    "trade_quality": 0.15,
    "pattern": 0.10,
    "alpha_eval": 0.15,
}
EPS = 0.01

# ── golden cases ──────────────────────────────────────────────────────────────
# 각 케이스: domain_coverage 딕셔너리 + raw_cap + 예상 출력
GOLDEN_CASES = [
    {
        "id": "GC-001: all zeros (현재 실측)",
        "domain_coverage": {"fundamental_core": 0.0, "realized_outcome": 0.6667, "trade_quality": 0.0, "pattern": 0.0, "alpha_eval": 0.0},
        "raw_cap": 93.0,
        "fund_core_coverage": 0.0,
        "t20_sample": 0,
        "expected_gate": "IMPUTED_DATA_BLOCK",
        "expected_imputed_ratio": 0.80,
        "expected_honest_cap": 48.4,
        "expected_long_horizon": False,
        "expected_fund_claim": False,
    },
    {
        "id": "GC-002: 펀더멘털만 50% 채움",
        # wc = 0.30×0.50 = 0.15; ifr = 0.85; ech = 93×(0.4+0.6×0.15) = 93×0.49 = 45.6
        "domain_coverage": {"fundamental_core": 0.50, "realized_outcome": 0.0, "trade_quality": 0.0, "pattern": 0.0, "alpha_eval": 0.0},
        "raw_cap": 93.0,
        "fund_core_coverage": 0.50,
        "t20_sample": 0,
        "expected_gate": "IMPUTED_DATA_BLOCK",
        "expected_imputed_ratio": 0.85,
        "expected_honest_cap": 45.6,
        "expected_long_horizon": False,
        "expected_fund_claim": True,  # 0.50 >= min_coverage
    },
    {
        "id": "GC-003: 전체 커버리지 68% (WARN 구간)",
        # wc = 0.30×0.80+0.30×0.80+0.15×0.50+0.10×0.50+0.15×0.50 = 0.68; ifr=0.32; ech=75.1
        "domain_coverage": {"fundamental_core": 0.80, "realized_outcome": 0.80, "trade_quality": 0.50, "pattern": 0.50, "alpha_eval": 0.50},
        "raw_cap": 93.0,
        "fund_core_coverage": 0.80,
        "t20_sample": 10,
        "expected_gate": "IMPUTED_DATA_WARN",
        "expected_imputed_ratio": 0.32,
        "expected_honest_cap": 75.1,
        "expected_long_horizon": True,
        "expected_fund_claim": True,
    },
    {
        "id": "GC-004: 완전 커버리지 (PASS)",
        "domain_coverage": {"fundamental_core": 1.0, "realized_outcome": 1.0, "trade_quality": 1.0, "pattern": 1.0, "alpha_eval": 1.0},
        "raw_cap": 93.0,
        "fund_core_coverage": 1.0,
        "t20_sample": 50,
        "expected_gate": "PASS",
        "expected_imputed_ratio": 0.0,
        "expected_honest_cap": 93.0,
        "expected_long_horizon": True,
        "expected_fund_claim": True,
    },
    {
        "id": "GC-005: 실현성과만 없음 (t20=0)",
        "domain_coverage": {"fundamental_core": 1.0, "realized_outcome": 0.333, "trade_quality": 1.0, "pattern": 1.0, "alpha_eval": 1.0},
        "raw_cap": 93.0,
        "fund_core_coverage": 1.0,
        "t20_sample": 0,
        "expected_gate": "PASS",      # imputed = 1 - 0.8=0.2 < 0.25 → PASS
        "expected_imputed_ratio": 0.2,
        "expected_honest_cap": 81.8,
        "expected_long_horizon": False,  # t20=0 → false
        "expected_fund_claim": True,
    },
]


def compute(case: dict) -> dict:
    dc = case["domain_coverage"]
    raw = case["raw_cap"]
    fund_cov = case["fund_core_coverage"]
    t20 = case["t20_sample"]

    wc = sum(DOMAIN_WEIGHTS[k] * v for k, v in dc.items())
    ifr = 1.0 - wc
    ech = raw * (0.4 + 0.6 * wc)

    if ifr >= BLOCK_RATIO:
        gate = "IMPUTED_DATA_BLOCK"
    elif ifr >= WARN_RATIO:
        gate = "IMPUTED_DATA_WARN"
    else:
        gate = "PASS"

    fund_claim = fund_cov >= FUND_FACTOR_MIN_COVERAGE
    long_ok = (t20 > 0) and fund_claim

    return {
        "weighted_coverage": round(wc, 4),
        "imputed_field_ratio": round(ifr, 4),
        "effective_confidence_honest": round(ech, 1),
        "gate_status": gate,
        "long_horizon_allowed": long_ok,
        "fundamental_claim_allowed": fund_claim,
    }


def main() -> int:
    failures: list[str] = []

    for case in GOLDEN_CASES:
        got = compute(case)

        checks = [
            (got["gate_status"] == case["expected_gate"],
             f"gate: {got['gate_status']} != {case['expected_gate']}"),
            (abs(got["imputed_field_ratio"] - case["expected_imputed_ratio"]) <= EPS,
             f"imputed_ratio: {got['imputed_field_ratio']} != {case['expected_imputed_ratio']}"),
            (abs(got["effective_confidence_honest"] - case["expected_honest_cap"]) <= 0.5,
             f"honest_cap: {got['effective_confidence_honest']} != {case['expected_honest_cap']}"),
            (got["long_horizon_allowed"] == case["expected_long_horizon"],
             f"long_horizon: {got['long_horizon_allowed']} != {case['expected_long_horizon']}"),
            (got["fundamental_claim_allowed"] == case["expected_fund_claim"],
             f"fund_claim: {got['fundamental_claim_allowed']} != {case['expected_fund_claim']}"),
        ]

        case_ok = all(ok for ok, _ in checks)
        status = "PASS" if case_ok else "FAIL"
        print(f"[{status}] {case['id']}")
        if not case_ok:
            for ok, msg in checks:
                if not ok:
                    print(f"  MISMATCH: {msg}")
            failures.append(case["id"])

    print(f"\n{'='*50}")
    print(f"GOLDEN_CASES: {len(GOLDEN_CASES) - len(failures)}/{len(GOLDEN_CASES)} PASS")
    if failures:
        print(f"FAILED: {failures}")
        return 1
    print("ALL GOLDEN CASES PASSED")
    return 0


if __name__ == "__main__":
    sys.exit(main())
