"""test_task_1919.py - test_runner MANDATORY 복원 + full_suite 검증 테스트"""
import os
import sys

import pytest

# qc_verify.py 경로 추가
QC_DIR = "/home/jay/workspace/teams/dev1/qc"
sys.path.insert(0, QC_DIR)


# ── 시나리오 1: test_runner는 MANDATORY이므로 --skip으로 건너뛸 수 없다 ──────────────
def test_skip_test_runner_blocked_by_mandatory():
    """test_runner는 MANDATORY이므로 --skip으로 건너뛸 수 없다."""
    # qc_verify의 MANDATORY_CHECKS에 "test_runner"가 있는지 확인
    # run_check("test_runner", skip_list=["test_runner"], ...) 호출 시
    # 여전히 MANUAL_SKIP을 반환하지만, main()에서 MANDATORY 차단이 작동
    from qc_verify import MANDATORY_CHECKS
    assert "test_runner" in MANDATORY_CHECKS, "test_runner가 MANDATORY_CHECKS에 있어야 함"


# ── 시나리오 2: full_suite_check가 ALL_CHECKS에 포함 (WARN 기록용) ────────────────
def test_full_suite_check_in_all_checks():
    """full_suite_check가 ALL_CHECKS에 포함되어 있다."""
    from qc_verify import ALL_CHECKS
    assert "full_suite_check" in ALL_CHECKS


# ── 시나리오 3: full_suite=True 실행 시 전체 tests/ 실행 확인 ──────────────────────
def test_full_suite_runs_all_tests(tmp_path, monkeypatch):
    """full_suite=True면 workspace tests/ 전체를 실행한다."""
    import verifiers.test_runner as tr

    # 임시 tests 디렉토리에 테스트 파일 생성
    tests_dir = tmp_path / "tests"
    tests_dir.mkdir()

    test1 = tests_dir / "test_a.py"
    test1.write_text("def test_a():\n    assert True\n")

    test2 = tests_dir / "test_b.py"
    test2.write_text("def test_b():\n    assert True\n")

    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))

    result = tr.verify(full_suite=True)
    assert result["status"] == "PASS", f"full_suite=True로 모든 테스트 통과 기대, got: {result}"
    # 실행 커맨드에 tests/ 디렉토리가 포함되어야 함
    details_str = "\n".join(result["details"])
    assert "tests" in details_str, f"tests 디렉토리 경로가 포함되어야 함, got: {details_str}"


# ── 시나리오 4: full_suite=True에서 실패 시 FAIL ───────────────────────────────────
def test_full_suite_fails_on_failure(tmp_path, monkeypatch):
    """full_suite=True에서 테스트 실패하면 FAIL 반환."""
    import verifiers.test_runner as tr

    tests_dir = tmp_path / "tests"
    tests_dir.mkdir()

    test_fail = tests_dir / "test_failing.py"
    test_fail.write_text("def test_fail():\n    assert False, 'intentional fail'\n")

    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))

    result = tr.verify(full_suite=True)
    assert result["status"] == "FAIL", f"실패 테스트가 있으면 FAIL 기대, got: {result}"


# ── 시나리오 5: full_suite_check FAIL → WARN 변환 확인 ────────────────────────────
def test_full_suite_check_fail_becomes_warn(tmp_path, monkeypatch):
    """full_suite_check에서 FAIL이 발생하면 WARN으로 변환된다."""
    import importlib
    import unittest.mock as _um

    # test_qc_gate.py 모듈 레벨에서 verifiers를 MagicMock으로 교체하므로 복원 필요
    for _n in list(sys.modules.keys()):
        if _n.startswith("verifiers") and isinstance(sys.modules[_n], _um.MagicMock):
            del sys.modules[_n]
    if "qc_verify" in sys.modules:
        importlib.reload(sys.modules["qc_verify"])

    from qc_verify import run_check

    # 실패하는 테스트를 가진 임시 workspace 설정
    tests_dir = tmp_path / "tests"
    tests_dir.mkdir()
    test_fail = tests_dir / "test_failing.py"
    test_fail.write_text("def test_fail():\n    assert False\n")
    monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))

    result = run_check(
        name="full_suite_check",
        skip_list=[],
        task_id="task-test",
        api_base="",
        api_endpoints=[],
        test_dir="",
        file_paths=[],
    )
    assert result["status"] == "WARN", f"full_suite FAIL → WARN 변환 기대, got: {result}"
    details_str = "\n".join(result["details"])
    assert "WARN 변환" in details_str


# ── 시나리오 6: g3 cross_verify 함수 테스트 ───────────────────────────────────────
def test_parse_report_test_results():
    """보고서에서 passed/failed 숫자를 파싱한다."""
    import sys
    sys.path.insert(0, "/home/jay/workspace/scripts")
    from g3_independent_verifier import parse_report_test_results

    content = "pytest 결과: 12 passed, 0 failed in 1.5s"
    result = parse_report_test_results(content)
    assert result is not None
    assert result["passed"] == 12
    assert result["failed"] == 0

    content2 = "5 passed, 3 failed in 2.1s"
    result2 = parse_report_test_results(content2)
    assert result2 is not None
    assert result2["passed"] == 5
    assert result2["failed"] == 3


def test_parse_report_test_results_no_pattern():
    """테스트 결과가 없으면 None 반환."""
    import sys
    sys.path.insert(0, "/home/jay/workspace/scripts")
    from g3_independent_verifier import parse_report_test_results

    content = "이 보고서에는 테스트 결과가 없습니다."
    result = parse_report_test_results(content)
    assert result is None
