"""
통합 테스트: prompts/gate_instructions.py
task-1837_5.1 - 엔키 작성
"""

import sys

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

from prompts.gate_instructions import (
    GATE_INSTRUCTIONS,
    format_for_prompt,
    get_codex_gate_command,
    get_gate_instructions,
    should_run_codex_check,
)


# ── 1. get_gate_instructions ────────────────────────────────────────────────

def test_get_gate_instructions_returns_correct_dict_for_each_level():
    """레벨 0~4 각각에 맞는 게이트 dict가 반환되어야 한다."""
    for level in range(5):
        result = get_gate_instructions(level)
        assert isinstance(result, dict), f"level={level} 반환값이 dict가 아님"
        assert "g1" in result
        assert "g2" in result
        assert "g3" in result
        # GATE_INSTRUCTIONS 원본과 일치해야 함
        assert result == GATE_INSTRUCTIONS[level]


def test_get_gate_instructions_fallback_for_unknown_level():
    """정의되지 않은 레벨(예: 99)이면 GATE_INSTRUCTIONS[0]을 반환해야 한다."""
    result = get_gate_instructions(99)
    assert result == GATE_INSTRUCTIONS[0]


def test_get_gate_instructions_level0_and_1_have_empty_g1():
    """레벨 0, 1은 g1이 빈 문자열이어야 한다."""
    for level in (0, 1):
        g = get_gate_instructions(level)
        assert g["g1"] == "", f"level={level} g1이 비어있지 않음: {g['g1']!r}"


def test_get_gate_instructions_level3_and_4_have_nonempty_g1():
    """레벨 3, 4는 g1이 비어있지 않아야 하며 sanitize 키워드를 포함해야 한다."""
    for level in (3, 4):
        g = get_gate_instructions(level)
        assert g["g1"], f"level={level} g1이 비어있음"
        assert "sanitize" in g["g1"].lower(), f"level={level} g1에 sanitize 없음"


# ── 2. format_for_prompt ─────────────────────────────────────────────────────

def test_format_for_prompt_level0_no_g1_section():
    """레벨 0은 g1이 비어있으므로 [G1 설계 게이트] 섹션이 없어야 한다."""
    output = format_for_prompt(0)
    assert "[G1 설계 게이트]" not in output


def test_format_for_prompt_level1_no_g1_section():
    """레벨 1도 g1이 비어있으므로 [G1 설계 게이트] 섹션이 없어야 한다."""
    output = format_for_prompt(1)
    assert "[G1 설계 게이트]" not in output
    assert "[G2 구현 게이트]" in output
    assert "[G3 머지 게이트]" in output


def test_format_for_prompt_level3_contains_sanitize():
    """레벨 3은 sanitize 키워드가 포맷된 문자열에 포함되어야 한다."""
    output = format_for_prompt(3)
    assert "sanitize" in output.lower()
    assert "[G1 설계 게이트]" in output
    assert "[G2 구현 게이트]" in output
    assert "[G3 머지 게이트]" in output


def test_format_for_prompt_level4_contains_sanitize():
    """레벨 4도 sanitize 키워드가 포함되어야 한다."""
    output = format_for_prompt(4)
    assert "sanitize" in output.lower()


def test_format_for_prompt_level2_has_all_gates():
    """레벨 2는 g1, g2, g3 모두 비어있지 않으므로 3개 섹션 모두 있어야 한다."""
    output = format_for_prompt(2)
    assert "[G1 설계 게이트]" in output
    assert "[G2 구현 게이트]" in output
    assert "[G3 머지 게이트]" in output


# ── 3. should_run_codex_check ─────────────────────────────────────────────────

def test_should_run_codex_check_below_3_returns_false():
    """레벨 0, 1, 2는 False를 반환해야 한다."""
    for level in (0, 1, 2):
        assert should_run_codex_check(level) is False, f"level={level}이 True 반환"


def test_should_run_codex_check_3_and_above_returns_true():
    """레벨 3, 4는 True를 반환해야 한다."""
    for level in (3, 4):
        assert should_run_codex_check(level) is True, f"level={level}이 False 반환"


def test_should_run_codex_check_boundary():
    """경계값 레벨 3이 정확히 True인지 확인."""
    assert should_run_codex_check(3) is True
    assert should_run_codex_check(2) is False


# ── 4. get_codex_gate_command ─────────────────────────────────────────────────

def test_get_codex_gate_command_basic_structure():
    """기본 명령어 리스트 구조: python3, script_path, --task-file, path, --workspace 포함."""
    cmd = get_codex_gate_command(
        task_file="/tmp/task.md",
        affected_files=[],
        workspace_root="/home/jay/workspace",
    )
    assert isinstance(cmd, list)
    assert cmd[0] == "python3"
    assert "codex_gate_check.py" in cmd[1]
    assert "--task-file" in cmd
    assert "/tmp/task.md" in cmd
    assert "--workspace-root" in cmd
    assert "/home/jay/workspace" in cmd


def test_get_codex_gate_command_with_affected_files():
    """affected_files가 있으면 --affected-files 뒤에 파일들이 포함되어야 한다."""
    files = ["dispatch.py", "utils/logger.py"]
    cmd = get_codex_gate_command(
        task_file="/tmp/task.md",
        affected_files=files,
        workspace_root="/home/jay/workspace",
    )
    assert "--affected-files" in cmd
    idx = cmd.index("--affected-files")
    assert cmd[idx + 1] == "dispatch.py"
    assert cmd[idx + 2] == "utils/logger.py"


def test_get_codex_gate_command_without_affected_files():
    """affected_files가 빈 리스트면 --affected-files가 없어야 한다."""
    cmd = get_codex_gate_command(
        task_file="/tmp/task.md",
        affected_files=[],
        workspace_root="/home/jay/workspace",
    )
    assert "--affected-files" not in cmd


def test_get_codex_gate_command_uses_workspace_root():
    """workspace_root 인자가 script_path와 --workspace 값에 반영되어야 한다."""
    custom_root = "/custom/workspace"
    cmd = get_codex_gate_command(
        task_file="/tmp/task.md",
        affected_files=["a.py"],
        workspace_root=custom_root,
    )
    # script path에 custom_root 포함
    assert custom_root in cmd[1]
    # --workspace 값에도 custom_root 포함
    ws_idx = cmd.index("--workspace-root")
    assert cmd[ws_idx + 1] == custom_root
