"""record_stage_elapsed enum/입력 검증 회귀 테스트."""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

# workspace root → sys.path (기존 regression 테스트 패턴 준수)
_WORKSPACE = Path(__file__).resolve().parent.parent.parent.parent
if str(_WORKSPACE) in sys.path:
    sys.path.remove(str(_WORKSPACE))
sys.path.insert(0, str(_WORKSPACE))

from utils.finish_task_timing_logger import (  # noqa: E402  # pyright: ignore[reportMissingImports]
    VALID_STAGES,
    record_stage_elapsed,
)

_EXPECTED_STAGES = {
    "qc_verify",
    "scope_guard",
    "worktree_manager_finish",
    "gh_pr_check",
    "git_gate",
    "impact_scanner",
    "ci_preflight",
    "bg_cleanup",
    "g3_verifier",
    "g4_gemini_gate",
    "lv4_audit",
    "codex_gate",
    "unresolved_gate",
    "goal_assertions",
    "task_timer_end",
    "token_tracker",
    "notify_completion",
    "extract_followup",
}


def _patch_log_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
    target = tmp_path / "logs" / "finish-task-timing.jsonl"
    monkeypatch.setenv("FINISH_TASK_TIMING_LOG_PATH", str(target))
    return target


def test_invalid_stage_raises_value_error(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    _patch_log_path(monkeypatch, tmp_path)

    with pytest.raises(ValueError):
        record_stage_elapsed(
            stage_name="nonexistent_stage",
            elapsed_sec=1.0,
            task_id="task-2691",
            team_id="dev8",
        )


def test_valid_stages_constant_has_exactly_18() -> None:
    assert isinstance(VALID_STAGES, tuple)
    assert len(VALID_STAGES) == 18
    assert set(VALID_STAGES) == _EXPECTED_STAGES


def test_negative_elapsed_raises_value_error(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    _patch_log_path(monkeypatch, tmp_path)

    with pytest.raises(ValueError):
        record_stage_elapsed(
            stage_name="qc_verify",
            elapsed_sec=-1,
            task_id="task-2691",
            team_id="dev8",
        )
