from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


def test_validate_dotnet_idempotency_contract_passes() -> None:
    root = Path(__file__).resolve().parents[2]
    proc = subprocess.run(
        [sys.executable, str(root / "tools" / "validate_dotnet_idempotency_contract_v1.py")],
        cwd=root,
        capture_output=True,
        text=True,
    )
    assert proc.returncode == 0, proc.stdout + proc.stderr
    payload = json.loads(proc.stdout)
    assert payload["gate"] == "PASS"


def test_validate_dotnet_idempotency_contract_reports_missing_table() -> None:
    root = Path(__file__).resolve().parents[2]
    temp = root / "Temp" / "test_wbs_10_idempotency_contract_bad.yaml"
    temp.write_text(
        "formula_id: WBS_10_DOTNET_IDEMPOTENCY_CONTRACT_V1\ngoal: 중복 실행 방지, lock/lease 정책, 재시도 경계를 표준화한다.\nlock_domain:\n  canonical_table: wrong\nidempotency_key:\n  required: true\nlease_policy:\n  required: true\n  retry_policy:\n    max_attempts: 3\n    backoff: exponential\nduplicate_execution_guards: [x]\n",
        encoding="utf-8",
    )
    proc = subprocess.run(
        [sys.executable, str(root / "tools" / "validate_dotnet_idempotency_contract_v1.py"), "--contract", str(temp)],
        cwd=root,
        capture_output=True,
        text=True,
    )
    assert proc.returncode != 0
    payload = json.loads(proc.stdout)
    assert payload["gate"] == "FAIL"
    assert "lock_domain.canonical_table" in payload["missing"]
