"""tests/regression/test_dotphase_compat_2487.py — task-2487 회귀 (legacy dot-phase, task-2547 corrected).

verifier/dispatch path 의 legacy dot-phase 호환 회복 검증.
PR #51 Gemini high: task-1234.5 거부 회귀 픽스용.
"""
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

import pytest

WORKSPACE = Path(__file__).resolve().parents[2]

_BROWSER_VERIFY_SSOT_PENDING = (
    "main에 browser_verify SSOT 위임 미적용 (PR #97 corrected scope 4 files만 머지). "
    "task-2487 chain 후속 PR에서 verifier 9개 SSOT 동기화 후 활성화 (회장 §명시 task-2551)."
)


def _load_module(mod_name: str, file_rel: str):
    file_path = WORKSPACE / file_rel
    spec = importlib.util.spec_from_file_location(mod_name, str(file_path))
    if spec is None or spec.loader is None:
        raise ImportError(f"cannot load spec for {file_path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[mod_name] = module
    spec.loader.exec_module(module)
    return module


tip = _load_module("tip_2487_dotphase", "utils/task_id_parser.py")


def test_legacy_dotphase_basic_pass():
    assert tip.is_valid_task_id_with_legacy("task-9.1") is True
    assert tip.is_valid_task_id_with_legacy("task-1234.5") is True


def test_legacy_dotphase_with_dev_suffix():
    assert tip.is_valid_task_id_with_legacy("task-648.1.dev1") is True
    assert tip.is_valid_task_id_with_legacy("task-648.1.dev1.done") is True


def test_v2_strict_rejects_dotphase():
    """is_valid_task_id (V2 strict) 는 dot-phase 를 거부한다."""
    assert tip.is_valid_task_id("task-1234.5") is False
    assert tip.is_valid_task_id("task-9.1") is False


def test_legacy_func_accepts_both_v2_and_legacy():
    """is_valid_task_id_with_legacy 는 V2와 legacy 양쪽 모두 받는다."""
    samples_v2 = ["task-2487", "task-2487+1", "task-2469_1.2_a+3"]
    samples_legacy = ["task-1234.5", "task-9.1", "task-648.1.dev1"]
    for s in samples_v2 + samples_legacy:
        assert tip.is_valid_task_id_with_legacy(s) is True, f"{s} should pass"


@pytest.mark.skip(reason=_BROWSER_VERIFY_SSOT_PENDING)
def test_browser_verify_uses_legacy_compat():
    """teams/shared/verifiers/browser_verify.py 가 is_valid_task_id_with_legacy 를 호출한다."""
    src = (WORKSPACE / "teams" / "shared" / "verifiers" / "browser_verify.py").read_text(encoding="utf-8")
    assert "is_valid_task_id_with_legacy" in src, (
        "browser_verify.py가 is_valid_task_id_with_legacy 를 사용하지 않음 — legacy 거부 회귀 가능"
    )


@pytest.mark.skip(reason=_BROWSER_VERIFY_SSOT_PENDING)
def test_browser_verify_no_strict_v2_only_in_verify():
    """browser_verify.verify 가 V2 strict (is_valid_task_id) 만 사용하지 않는지 검증."""
    src = (WORKSPACE / "teams" / "shared" / "verifiers" / "browser_verify.py").read_text(encoding="utf-8")
    # verify() 함수 내부에 is_valid_task_id_with_legacy 가 있어야 함
    assert "is_valid_task_id_with_legacy(task_id)" in src, (
        "browser_verify.verify 가 V2+legacy 통합 검증을 사용하지 않음"
    )
