"""
test_finish_task_gates.py — finish-task.sh 게이트 통합 테스트
모리건(개발3팀 테스터) 작성
task-2152
"""

import re
import subprocess
import sys

# utils 패키지를 import할 수 있도록 workspace 경로 추가
sys.path.insert(0, "/home/jay/workspace")


def test_gate_config_all_gates():
    """5개 게이트가 모두 gate-config.json에 존재하고 정상 반환"""
    from utils.gate_config_loader import load_gate_config

    gates = ["impact_scanner", "ci_preflight", "l1_smoketest", "goal_assertions", "unresolved_gate"]
    for gate in gates:
        cfg = load_gate_config(gate)
        assert "enabled" in cfg
        assert "mode" in cfg
        assert isinstance(cfg["enabled"], bool)
        assert cfg["mode"] in ("warn", "fail")


def test_gate_results_schema():
    """gate_results 딕셔너리가 5개 필드를 모두 포함하는 스키마"""
    expected_keys = {"impact_scanner", "ci_preflight", "l1_smoketest", "goal_assertions", "unresolved_gate"}
    with open("/home/jay/workspace/scripts/finish-task.sh") as f:
        content = f.read()
    # gate_results 블록 추출
    match = re.search(r"'gate_results':\s*\{([^}]+)\}", content)
    assert match, "gate_results 블록이 finish-task.sh에 존재해야 함"
    block = match.group(1)
    for key in expected_keys:
        assert key in block, f"gate_results에 {key} 키가 없음"


def test_task_timer_preserves_gate_results():
    """task-timer.py에 gate_results 보존 로직이 존재"""
    with open("/home/jay/workspace/memory/task-timer.py") as f:
        content = f.read()
    assert "existing_extra" in content, "existing_extra 변수가 존재해야 함"
    assert "gate_results" in content, "gate_results 보존 로직이 존재해야 함"
    assert "event.update(existing_extra)" in content, "existing_extra를 event에 merge해야 함"


def test_goal_assertions_allowed_commands():
    """goal_assertions의 allowed_commands가 gate-config.json에 정의되어 있음"""
    from utils.gate_config_loader import load_gate_config

    cfg = load_gate_config("goal_assertions")
    allowed = cfg.get("allowed_commands", [])
    assert len(allowed) > 0, "allowed_commands가 비어있으면 안 됨"
    assert "grep" in allowed
    assert "python3" in allowed
    # 위험 명령이 없어야 함
    dangerous = {"rm", "dd", "mkfs", "chmod", "chown", "sudo"}
    for cmd in dangerous:
        assert cmd not in allowed, f"위험 명령 {cmd}이 allowed_commands에 포함됨"


def test_finish_task_bash_syntax():
    """finish-task.sh의 bash 구문이 유효함"""
    result = subprocess.run(
        ["bash", "-n", "/home/jay/workspace/scripts/finish-task.sh"],
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, f"bash syntax error: {result.stderr}"


def test_set_e_isolation():
    """각 게이트에 set +e/set -e 격리가 있음"""
    with open("/home/jay/workspace/scripts/finish-task.sh") as f:
        content = f.read()
    # Impact Scanner와 CI Preflight에 set +e/set -e 쌍이 있는지
    pattern_impact = r"# 2\.6\. Impact.*?set \+e.*?set -e"
    pattern_ci = r"# 2\.6\.5\. CI Preflight.*?set \+e.*?set -e"
    assert re.search(pattern_impact, content, re.DOTALL), "Impact Scanner에 set +e/set -e 격리 없음"
    assert re.search(pattern_ci, content, re.DOTALL), "CI Preflight에 set +e/set -e 격리 없음"
