"""P1-7 hooks 자동 강제 테스트."""

import json
import os
import sys
from pathlib import Path

sys.path.insert(0, "/home/jay/workspace")
sys.path.insert(0, "/home/jay/workspace/hooks")

from hooks.circuit_breaker import cmd_check, cmd_record, cmd_reset


# TC-HK-04: circuit breaker warning 15회 누적 후 halt
def test_circuit_breaker_warning_threshold(tmp_path):
    state_path = str(tmp_path / "cb_state.json")
    for i in range(14):
        # 연속 3-tuple 발동을 피하기 위해 파일명을 순환
        result = cmd_record("standard", f"foo_{i}.py", "ruff_style_warning", state_path=state_path)
        assert result == "ok", f"Should be ok at iteration {i}"
    # 15번째
    result = cmd_record("standard", "foo_14.py", "ruff_style_warning", state_path=state_path)
    assert result == "halt", "Should halt at 15th warning"
    assert cmd_check("foo_14.py", state_path=state_path) == "halt"


# TC-HK-05: 3-tuple 연속 3회 halt
def test_circuit_breaker_consecutive_tuple(tmp_path):
    state_path = str(tmp_path / "cb_state.json")
    for _ in range(2):
        result = cmd_record("standard", "foo.py", "ruff_style_warning", tool="Write", state_path=state_path)
    # 3번째에서 halt
    result = cmd_record("standard", "foo.py", "ruff_style_warning", tool="Write", state_path=state_path)
    assert result == "halt", "Should halt at 3rd consecutive same tuple"


# TC-HK-06: 플래그 비활성화 확인
def test_flag_disabled_hook_skipped(tmp_path):
    import json

    from utils.feature_flags import FeatureFlagLoader

    # 실제 파일 대신 hooks_enforcement_enabled=False인 임시 파일 사용
    flags_file = tmp_path / "feature_flags.json"
    data = {
        "schema_version": "1.0",
        "flags": {
            "hooks_enforcement_enabled": False,
        },
    }
    flags_file.write_text(json.dumps(data), encoding="utf-8")
    loader = FeatureFlagLoader(path=str(flags_file))
    assert loader.is_enabled("hooks_enforcement_enabled") is False


# circuit breaker reset 테스트
def test_circuit_breaker_reset(tmp_path):
    state_path = str(tmp_path / "cb_state.json")
    # warning 누적
    for _ in range(15):
        cmd_record("standard", "foo.py", "ruff_style_warning", state_path=state_path)
    assert cmd_check("foo.py", state_path=state_path) == "halt"
    # reset
    cmd_reset(state_path=state_path)
    assert cmd_check("foo.py", state_path=state_path) == "ok"


# circuit breaker critical threshold 테스트
def test_circuit_breaker_critical_threshold(tmp_path):
    state_path = str(tmp_path / "cb_state.json")
    for i in range(29):
        # 연속 3-tuple 발동을 피하기 위해 파일명을 순환
        result = cmd_record("critical", f"bar_{i}.py", "pyright_type_error", state_path=state_path)
        assert result == "ok", f"Should be ok at critical iteration {i}"
    result = cmd_record("critical", "bar_29.py", "pyright_type_error", state_path=state_path)
    assert result == "halt", "Should halt at 30th critical"


# 3-tuple 연속 판별이 다른 이벤트가 끼면 리셋되는지 확인
def test_consecutive_tuple_broken_by_different_event(tmp_path):
    state_path = str(tmp_path / "cb_state.json")
    cmd_record("standard", "foo.py", "ruff_style_warning", tool="Write", state_path=state_path)
    cmd_record("standard", "foo.py", "ruff_style_warning", tool="Write", state_path=state_path)
    # 다른 이벤트 삽입
    cmd_record("standard", "bar.py", "ruff_style_warning", tool="Write", state_path=state_path)
    # 다시 foo.py - 연속이 깨져야 함
    result = cmd_record("standard", "foo.py", "ruff_style_warning", tool="Write", state_path=state_path)
    assert result == "ok", "Consecutive should be broken by different event"


# settings.json 존재 확인
def test_settings_json_exists():
    settings_path = "/home/jay/workspace/.claude/settings.json"
    assert os.path.exists(settings_path), "settings.json should exist"
    with open(settings_path) as f:
        data = json.load(f)
    assert "hooks" in data
    assert "PostToolUse" in data["hooks"]


# QC-RULES.md hooks 규칙 존재 확인
def test_qc_rules_hooks_section():
    qc_path = "/home/jay/workspace/teams/shared/QC-RULES.md"
    content = Path(qc_path).read_text(encoding="utf-8")
    assert "hooks와 QC는 별개 의무" in content
    assert "hooks 통과 ≠ QC 면제" in content


# post_tool_use.sh 실행 권한 확인
def test_post_tool_use_sh_executable():
    sh_path = "/home/jay/workspace/hooks/post_tool_use.sh"
    assert os.path.exists(sh_path), "post_tool_use.sh should exist"
    assert os.access(sh_path, os.X_OK), "post_tool_use.sh should be executable"
