"""gstack 분석 검증 테스트 (task-837.1)

보고서의 핵심 내용이 올바르게 작성되었는지 검증합니다.
"""

import glob
import os
from pathlib import Path

import pytest

WORKSPACE_ROOT = Path(os.environ.get("WORKSPACE_ROOT", "/home/jay/workspace"))


def _find_gstack_report() -> Path | None:
    """gstack-analysis 보고서를 찾는다 (날짜 하드코딩 없이)."""
    pattern = str(WORKSPACE_ROOT / "memory" / "reports" / "gstack-analysis-*.md")
    matches = sorted(glob.glob(pattern), reverse=True)  # 최신 먼저
    return Path(matches[0]) if matches else None


def _find_done_file() -> Path | None:
    """task-837.1 done 파일을 표준 경로와 구 경로 모두에서 찾는다."""
    # 표준 경로 (현행)
    standard = WORKSPACE_ROOT / "memory" / "events" / "task-837.1.done"
    if standard.exists():
        return standard
    # 구 경로 (레거시)
    legacy = WORKSPACE_ROOT / "teams" / "dev3" / "task-837.1.done"
    if legacy.exists():
        return legacy
    return None


class TestGstackReportExists:
    """보고서 파일 존재 여부 검증"""

    def test_report_file_exists(self) -> None:
        """보고서 파일이 생성되어야 한다."""
        report_path = _find_gstack_report()
        assert report_path is not None, "gstack-analysis-*.md 보고서를 찾을 수 없습니다"
        assert report_path.exists()

    def test_report_has_content(self) -> None:
        """보고서에 내용이 있어야 한다."""
        report_path = _find_gstack_report()
        if report_path is None:
            pytest.skip("gstack-analysis 보고서 파일이 없습니다")
        content = report_path.read_text()
        assert len(content) > 1000, "Report content too short"
        assert "gstack" in content, "Report missing 'gstack' keyword"


class TestGstackReportSections:
    """보고서 섹션 구조 검증"""

    @pytest.fixture
    def report_content(self) -> str:
        report_path = _find_gstack_report()
        if report_path is None:
            pytest.skip("gstack-analysis 보고서 파일이 없습니다")
        return report_path.read_text()

    def test_has_overview_section(self, report_content: str) -> None:
        """개요 섹션이 있어야 한다."""
        assert "개요" in report_content or "## 1" in report_content

    def test_has_architecture_section(self, report_content: str) -> None:
        """아키텍처 섹션이 있어야 한다."""
        assert "아키텍처" in report_content or "Architecture" in report_content

    def test_has_skills_section(self, report_content: str) -> None:
        """스킬 섹션이 있어야 한다."""
        assert "스킬" in report_content or "Skills" in report_content or "## 3" in report_content

    def test_has_philosophy_section(self, report_content: str) -> None:
        """철학 섹션이 있어야 한다."""
        assert "철학" in report_content or "Philosophy" in report_content or "Boil the Lake" in report_content

    def test_has_comparison_section(self, report_content: str) -> None:
        """비교 섹션이 있어야 한다."""
        assert "비교" in report_content or "Comparison" in report_content or "우리 시스템" in report_content

    def test_has_conclusion_section(self, report_content: str) -> None:
        """결론 섹션이 있어야 한다."""
        assert "결론" in report_content or "Conclusion" in report_content


class TestGstackKeyConcepts:
    """핵심 개념 포함 여부 검증"""

    @pytest.fixture
    def report_content(self) -> str:
        report_path = _find_gstack_report()
        if report_path is None:
            pytest.skip("gstack-analysis 보고서 파일이 없습니다")
        return report_path.read_text()

    def test_boil_the_lake_mentioned(self, report_content: str) -> None:
        """Boil the Lake 철학이 언급되어야 한다."""
        assert "Boil the Lake" in report_content or "호수를 끓여라" in report_content

    def test_search_before_building_mentioned(self, report_content: str) -> None:
        """Search Before Building이 언급되어야 한다."""
        assert "Search Before Building" in report_content or "만들기 전에 검색" in report_content

    def test_ref_system_mentioned(self, report_content: str) -> None:
        """Ref 시스템이 언급되어야 한다."""
        assert "Ref" in report_content or "@e1" in report_content

    def test_fix_first_mentioned(self, report_content: str) -> None:
        """Fix-First가 언급되어야 한다."""
        assert "Fix-First" in report_content or "AUTO-FIX" in report_content

    def test_preamble_mentioned(self, report_content: str) -> None:
        """Preamble이 언급되어야 한다."""
        assert "Preamble" in report_content or "preamble" in report_content

    def test_garry_tan_mentioned(self, report_content: str) -> None:
        """Garry Tan이 언급되어야 한다."""
        assert "Garry Tan" in report_content or "garrytan" in report_content.lower()

    def test_y_combinator_mentioned(self, report_content: str) -> None:
        """Y Combinator가 언급되어야 한다."""
        assert "Y Combinator" in report_content or "YC" in report_content


class TestDoneFile:
    """완료 파일 검증"""

    def test_done_file_exists(self) -> None:
        """완료 파일이 생성되어야 한다."""
        done_path = _find_done_file()
        assert done_path is not None, "task-837.1 done 파일을 찾을 수 없습니다 (memory/events/ 또는 teams/dev3/)"

    def test_done_file_content(self) -> None:
        """완료 파일 내용이 유효해야 한다."""
        done_path = _find_done_file()
        if done_path is None:
            pytest.skip("task-837.1 done 파일이 없습니다")
        content = done_path.read_text().strip()
        # JSON 형식(현행 표준) 또는 텍스트 "done"(레거시) 모두 수용
        is_valid = content == "done" or (content.startswith("{") and "task_id" in content)
        assert is_valid, f"done 파일 내용이 유효하지 않음: {content[:100]}"
