from __future__ import annotations

import json
import runpy
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]


def test_awooop_controlled_automation_copy_guard_blocks_legacy_manual_gate_text() -> None:
    guard = runpy.run_path(
        str(ROOT / "scripts" / "security" / "awooop-controlled-automation-copy-guard.py")
    )

    guard["validate"](ROOT)


def test_awooop_controlled_automation_copy_guard_blocks_live_owner_review_copy(tmp_path: Path) -> None:
    guard = runpy.run_path(
        str(ROOT / "scripts" / "security" / "awooop-controlled-automation-copy-guard.py")
    )
    messages_path = tmp_path / "apps" / "web" / "messages" / "zh-TW.json"
    messages_path.parent.mkdir(parents=True)
    messages_path.write_text(
        json.dumps({"awooop": {"workItems": {"status": "Owner Review 等待人工"}}}),
        encoding="utf-8",
    )

    violations = guard["_collect_awooop_message_violations"](messages_path, tmp_path)

    assert any("Owner Review" in violation for violation in violations)
    assert any("等待人工" in violation for violation in violations)


def test_awooop_controlled_automation_copy_guard_blocks_serialized_manual_gate_copy(
    tmp_path: Path,
) -> None:
    guard = runpy.run_path(
        str(ROOT / "scripts" / "security" / "awooop-controlled-automation-copy-guard.py")
    )
    messages_path = tmp_path / "apps" / "web" / "messages" / "zh-TW.json"
    messages_path.parent.mkdir(parents=True)
    messages_path.write_text(
        json.dumps(
            {"governance": {"automationInventory": {"label": "人工 Gate"}}},
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )

    violations = guard["_collect_forbidden_line_violations"](
        messages_path,
        tmp_path,
        messages_path.read_text(encoding="utf-8"),
    )

    assert any("人工 Gate" in violation for violation in violations)


def test_awooop_controlled_automation_copy_guard_allows_legacy_hitl_history(tmp_path: Path) -> None:
    guard = runpy.run_path(
        str(ROOT / "scripts" / "security" / "awooop-controlled-automation-copy-guard.py")
    )
    messages_path = tmp_path / "apps" / "web" / "messages" / "zh-TW.json"
    messages_path.parent.mkdir(parents=True)
    messages_path.write_text(
        json.dumps({"awooop": {"approvals": {"legacyHitl": {"title": "既有 HITL 待人工處理"}}}}),
        encoding="utf-8",
    )

    violations = guard["_collect_awooop_message_violations"](messages_path, tmp_path)

    assert violations == []
