"""build_pass_100_criteria_v3.py — PASS_100_CRITERIA_V3 (단일 권위 버전)

P0-002: v1/v2 기준 충돌 해소. 이 파일이 유일한 active PASS_100 권위 산출물이다.
v1/v2는 legacy_reference_only=true로 폐기. final_execution_decision은 이 파일만 참조한다.
P0-003: remediation_type 추가 (DATA_GATED/OPERATIONAL_ACTION/CODE_FIXABLE/BUILDER_STALE).
        pass_100_criteria_v1.json에도 동시 기록 (v1은 v3의 alias).
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from v7_hardening_common import ROOT, TEMP, load_json, save_json

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")


DEFAULT_OUT = TEMP / "pass_100_criteria_v3.json"
ALIAS_OUT   = TEMP / "pass_100_criteria_v1.json"   # v3가 v1 alias를 덮어쓴다
IS_ACTIVE = True
LEGACY_FILES = ["pass_100_criteria_v2.json"]

# 해소 유형 상수
DATA_GATED        = "DATA_GATED"          # 운영 T+20 표본 축적 필요 (~2026-07)
OPERATIONAL_ACTION = "OPERATIONAL_ACTION"  # 사용자 HTS 캡처 등 수동 조치 필요
CODE_FIXABLE      = "CODE_FIXABLE"         # 코드/빌더로 즉시 해소 가능
BUILDER_STALE     = "BUILDER_STALE"        # 빌더 재실행으로 해소


def _criterion(
    criterion_id: str,
    actual: object,
    target: str,
    passed: bool,
    source_json: str,
    formula_id: str,
    remediation: str,
    remediation_type: str = CODE_FIXABLE,
    data_gated_until: str = "",
) -> dict[str, object]:
    row: dict[str, object] = {
        "criterion_id": criterion_id,
        "actual": actual,
        "target": target,
        "passed": bool(passed),
        "source_json": source_json,
        "formula_id": formula_id,
        "remediation": "NONE" if passed else remediation,
        "remediation_type": "NONE" if passed else remediation_type,
    }
    if not passed and data_gated_until:
        row["data_gated_until"] = data_gated_until
    return row


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

    truth = load_json(TEMP / "operational_truth_score_v1.json")
    decision = load_json(TEMP / "final_execution_decision_v2.json") or load_json(TEMP / "final_execution_decision_v1.json")
    matrix = load_json(TEMP / "execution_readiness_matrix_v1.json")
    dq = load_json(TEMP / "data_quality_reconciliation_v1.json")
    # SCR은 v7 우선 (execution_allowed 필드 있는 최신; v8=None, v9=다른 스키마 제외)
    scr = (
        load_json(TEMP / "smart_cash_recovery_v7.json")
        or load_json(TEMP / "smart_cash_recovery_v6.json")
    )
    hardening = load_json(TEMP / "strategy_hardening_harness_v2.json")
    stl = load_json(TEMP / "single_truth_ledger_v2.json")
    agp = load_json(TEMP / "algorithm_guidance_proof_v1.json")

    # RELEASE_GATE_TRUTH_V1: honest_proof_score >= 70 이어야만 릴리스 허용 (RC1 수정)
    _honest_score = float(agp.get("honest_proof_score") or 0)
    _honest_gate = str(agp.get("honest_gate") or "FAIL")
    _cosmetic_gate = str(agp.get("gate") or "FAIL")
    _effective_release_gate = "PASS" if (_honest_gate == "PASS" and _cosmetic_gate == "PASS") else "FAIL"

    # SCR source 파일명 (보고용) — v7/v6 체인
    _scr_src = (
        "smart_cash_recovery_v7.json" if load_json(TEMP / "smart_cash_recovery_v7.json")
        else "smart_cash_recovery_v6.json"
    )
    _scr_damage = float(scr.get("value_damage_pct_avg") or 0)
    _scr_damage_raw = float(scr.get("value_damage_pct_avg_raw") or scr.get("value_damage_pct_avg") or 0)

    criteria = [
        _criterion(
            "RELEASE_GATE_TRUTH_V1",
            {"honest_proof_score": _honest_score, "honest_gate": _honest_gate,
             "cosmetic_gate": _cosmetic_gate, "effective_release_gate": _effective_release_gate},
            "honest_proof_score >= 70.0 AND honest_gate == PASS",
            _honest_score >= 70.0 and _honest_gate == "PASS",
            "algorithm_guidance_proof_v1.json",
            "RELEASE_GATE_TRUTH_V1",
            "honest_proof_score < 70 → T+20 표본 30건 축적 후 자동 해소 (~2026-07)",
            remediation_type=DATA_GATED,
            data_gated_until="2026-07-15",
        ),
        _criterion(
            "SCHEMA_PRESENCE_100",
            dq.get("schema_presence_score"),
            "== 100",
            float(dq.get("schema_presence_score") or 0) == 100.0,
            "data_quality_reconciliation_v1.json",
            "DATA_QUALITY_RECONCILIATION_V1",
            "restore required JSON collections",
            remediation_type=CODE_FIXABLE,
        ),
        _criterion(
            "FORMULA_RUNTIME_COVERAGE_100",
            hardening.get("domain_scores", {}).get("formula_runtime_coverage_pct"),
            "== 100",
            float(hardening.get("domain_scores", {}).get("formula_runtime_coverage_pct") or 0) == 100.0,
            "strategy_hardening_harness_v2.json",
            "STRATEGY_HARDENING_HARNESS_V2",
            "map every YAML formula to runtime code",
            remediation_type=CODE_FIXABLE,
        ),
        _criterion(
            "CONFIDENCE_CAP_BASIS_GE_90",
            dq.get("confidence_cap_basis_score"),
            ">= 90",
            float(dq.get("confidence_cap_basis_score") or 0) >= 90.0,
            "data_quality_reconciliation_v1.json",
            "DATA_QUALITY_RECONCILIATION_V1",
            "fill actual investment-quality evidence",
            remediation_type=CODE_FIXABLE,
        ),
        _criterion(
            "SINGLE_TRUTH_NO_CONFLICT",
            stl.get("conflict_count"),
            "== 0",
            int(stl.get("conflict_count") or 0) == 0,
            "single_truth_ledger_v2.json",
            "SINGLE_TRUTH_LEDGER_V2",
            "resolve source_value_recheck mismatches in ledger",
            remediation_type=CODE_FIXABLE,
        ),
        _criterion(
            "OPERATIONAL_TRUTH_SCORE_100",
            truth.get("score_0_100"),
            "== 100 and gate PASS_100",
            float(truth.get("score_0_100") or 0) == 100.0 and str(truth.get("gate") or "") == "PASS_100",
            "operational_truth_score_v1.json",
            "OPERATIONAL_TRUTH_SCORE_V1",
            "export_gate 해소(HTS 캡처) + performance_readiness 해소 필요",
            remediation_type=DATA_GATED,
            data_gated_until="2026-07-15",
        ),
        _criterion(
            "EXECUTION_TRUTH_SCORE_100",
            truth.get("execution_truth_score"),
            "== 100",
            float(truth.get("execution_truth_score") or 0) == 100.0,
            "operational_truth_score_v1.json",
            "OPERATIONAL_TRUTH_SCORE_V1",
            "HTS 캡처 → export_gate PASS → execution_truth 자동 해소",
            remediation_type=OPERATIONAL_ACTION,
        ),
        _criterion(
            "PERFORMANCE_READINESS_GE_90",
            truth.get("performance_readiness_score"),
            ">= 90 and readiness_gate PERFORMANCE_READY",
            float(truth.get("performance_readiness_score") or 0) >= 90.0,
            "operational_truth_score_v1.json",
            "OPERATIONAL_TRUTH_SCORE_V1",
            "T+20 운영 표본 30건 필요 — 매일 자동 축적 (~2026-07-05~07-15)",
            remediation_type=DATA_GATED,
            data_gated_until="2026-07-15",
        ),
        _criterion(
            "SMART_CASH_VALUE_DAMAGE_LE_10",
            {"value_damage_adj": _scr_damage, "value_damage_raw": _scr_damage_raw, "source": _scr_src},
            "<= 10 (adj and raw)",
            _scr_damage <= 10.0 and _scr_damage_raw <= 10.0,
            _scr_src,
            scr.get("formula_id") or "SMART_CASH_RECOVERY",
            "build-execution-readiness-matrix-v1 재실행으로 해소 (stale 12.5% → 현재 0.0%)",
            remediation_type=BUILDER_STALE,
        ),
        _criterion(
            "SMART_CASH_EXECUTION_ALLOWED",
            scr.get("execution_allowed"),
            "is true and status PASS",
            bool(scr.get("execution_allowed")) and str(scr.get("status") or "") == "PASS",
            _scr_src,
            scr.get("formula_id") or "SMART_CASH_RECOVERY",
            "clear smart cash recovery hard blocks",
            remediation_type=CODE_FIXABLE,
        ),
        _criterion(
            "FINAL_EXECUTION_HTS_READY",
            decision.get("global_execution_gate"),
            "HTS_READY",
            str(decision.get("global_execution_gate") or "") == "HTS_READY",
            "final_execution_decision_v2.json",
            "FINAL_EXECUTION_DECISION_V2",
            "PERFORMANCE_READINESS_GE_90 해소 후 자동 연쇄 해소 (~2026-07-15)",
            remediation_type=DATA_GATED,
            data_gated_until="2026-07-15",
        ),
        _criterion(
            "HTS_ORDER_COUNT_GT_0",
            decision.get("hts_order_count"),
            "> 0",
            int(decision.get("hts_order_count") or 0) > 0,
            "final_execution_decision_v2.json",
            "FINAL_EXECUTION_DECISION_V2",
            "FINAL_EXECUTION_HTS_READY 해소 후 자동 연쇄 해소 (~2026-07-15)",
            remediation_type=DATA_GATED,
            data_gated_until="2026-07-15",
        ),
        _criterion(
            "EXECUTION_READINESS_MATRIX_PASS_100",
            {"gate": matrix.get("gate"), "min_axis_score": matrix.get("min_axis_score")},
            "gate PASS_100 and min_axis_score 100",
            str(matrix.get("gate") or "") == "PASS_100" and float(matrix.get("min_axis_score") or 0) == 100.0,
            "execution_readiness_matrix_v1.json",
            "EXECUTION_READINESS_MATRIX_V1",
            "HTS 캡처(OPERATIONAL_ACTION) + T+20 표본 축적(DATA_GATED) 후 자동 해소",
            remediation_type=OPERATIONAL_ACTION,
        ),
    ]

    failed = [row for row in criteria if not row["passed"]]
    score = round((len(criteria) - len(failed)) / len(criteria) * 100.0, 2)

    result = {
        "formula_id": "PASS_100_CRITERIA_V3",
        "is_active": IS_ACTIVE,
        "authority_note": "유일한 active PASS_100 기준. v1/v2는 legacy_reference_only.",
        "legacy_files": LEGACY_FILES,
        "gate": "PASS_100" if not failed else "BLOCK_EXECUTION",
        "pass_100_allowed": not failed,
        "score_0_100": score,
        "passed_count": len(criteria) - len(failed),
        "failed_count": len(failed),
        "failed_criteria": [str(row["criterion_id"]) for row in failed],
        "criteria": criteria,
        "effective_release_gate": _effective_release_gate,
        "release_gate_note": (
            f"[RELEASE_BLOCKED_BY_TRUTH_GATE: honest={_honest_score} < 70]"
            if _honest_score < 70.0 else "RELEASE_GATE_TRUTH PASS"
        ),
        "hts_order_mode": (
            "THEORETICAL_ONLY" if _honest_score < 70.0 else "HTS_ALLOWED"
        ),
        "targets": {
            "completion_definition": "PASS_100 only when every criterion passed",
            "hts_execution_definition": "HTS execution forbidden unless FINAL_EXECUTION_HTS_READY and HTS_ORDER_COUNT_GT_0 pass",
            "llm_role": "copy criteria and render ledgers only; no ad-hoc numeric overrides",
            "release_gate_truth_definition": "effective_release_gate = AND(cosmetic_gate, honest_gate); honest_proof_score < 70 → THEORETICAL_ONLY",
        },
    }
    save_json(args.out, result)
    # v1은 v3의 alias — 동일 내용을 v1에도 저장해 기존 코드가 v1을 읽어도 최신 데이터를 얻도록 한다
    alias_result = dict(result, formula_id="PASS_100_CRITERIA_V3_ALIAS_V1",
                        alias_note="이 파일은 pass_100_criteria_v3.json의 alias입니다. build_pass_100_criteria_v3.py가 권위 소스입니다.")
    save_json(ALIAS_OUT, alias_result)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


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