"""validate_pass_100_authority_lock_v1.py — P0-002 수용 검증기

active PASS_100 산출물이 정확히 1개이고 v3가 그것임을 검증한다.
legacy v1/v2에는 legacy_reference_only 마킹이 있어야 한다.
"""
from __future__ import annotations

import json
from pathlib import Path

from v7_hardening_common import ROOT, TEMP, load_json, save_json

DEFAULT_OUT = TEMP / "pass_100_authority_lock_v1.json"


def main() -> int:
    v3 = load_json(TEMP / "pass_100_criteria_v3.json")
    v2 = load_json(TEMP / "pass_100_criteria_v2.json")
    v1 = load_json(TEMP / "pass_100_criteria_v1.json")

    errors: list[str] = []

    # v3 must be active
    if not v3:
        errors.append("pass_100_criteria_v3.json not found — run build_pass_100_criteria_v3.py first")
    elif not v3.get("is_active"):
        errors.append("pass_100_criteria_v3.json.is_active != true")

    # v3 must be the only active artifact
    if v2 and v2.get("is_active"):
        errors.append("pass_100_criteria_v2.json still has is_active=true — must be legacy_reference_only")
    if v1 and v1.get("is_active"):
        errors.append("pass_100_criteria_v1.json still has is_active=true — must be legacy_reference_only")

    # active PASS_100 not achieving PASS_100 when failed_count>0 is correct behaviour
    # but authority lock must exist
    active_artifact_count = sum([
        1 if (v3 and v3.get("is_active")) else 0,
        1 if (v2 and v2.get("is_active")) else 0,
        1 if (v1 and v1.get("is_active")) else 0,
    ])

    if active_artifact_count != 1:
        errors.append(f"active_artifact_count={active_artifact_count}, expected exactly 1 (pass_100_criteria_v3.json)")

    status = "PASS" if not errors else "FAIL"
    result = {
        "formula_id": "PASS_100_AUTHORITY_LOCK_V1",
        "status": status,
        "active_artifact": "pass_100_criteria_v3.json",
        "active_artifact_count": active_artifact_count,
        "errors": errors,
        "v3_gate": v3.get("gate") if v3 else "MISSING",
        "v3_score_0_100": v3.get("score_0_100") if v3 else None,
        "v3_failed_count": v3.get("failed_count") if v3 else None,
    }
    save_json(str(DEFAULT_OUT), result)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    if status == "PASS":
        print("PASS_100_AUTHORITY_LOCK_V1_OK")
    else:
        print("PASS_100_AUTHORITY_LOCK_V1_FAIL")
        for e in errors:
            print(f"  ERROR: {e}")
    return 0 if status == "PASS" else 1


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