"""task-1058.1: Before Starting 명칭 통일 테스트

모든 SKILL.md 파일에서 "시작 전 확인" 섹션이 "Before Starting"으로 통일되었는지 검증.
"""

import re
from pathlib import Path

import pytest

SKILLS_DIR = Path("/home/jay/.claude/skills")

# DEPRECATED 파일들 (섹션 헤더가 없어도 됨)
DEPRECATED_SKILLS = {"conversion-copywriter"}


class TestBeforeStartingUnification:
    """Before Starting 명칭 통일 테스트."""

    @pytest.fixture
    def skill_files(self) -> list[Path]:
        """모든 SKILL.md 파일 목록."""
        return list(SKILLS_DIR.glob("*/SKILL.md"))

    def test_all_skill_files_exist(self, skill_files: list[Path]) -> None:
        """SKILL.md 파일이 존재해야 함."""
        assert len(skill_files) > 0, "SKILL.md 파일이 없음"

    def test_no_korean_before_starting(self, skill_files: list[Path]) -> None:
        """모든 파일에서 '시작 전 확인' 섹션 헤더가 없어야 함."""
        korean_pattern = re.compile(r"^## .*시작 전.*$", re.MULTILINE)

        violations = []
        for filepath in skill_files:
            # DEPRECATED 파일은 건너뜀
            if filepath.parent.name in DEPRECATED_SKILLS:
                continue

            try:
                content = filepath.read_text(encoding="utf-8")
                matches = korean_pattern.findall(content)
                if matches:
                    violations.append((filepath, matches))
            except Exception as e:
                violations.append((filepath, [f"Error: {e}"]))

        assert len(violations) == 0, f"한국어 '시작 전 확인' 섹션 발견:\n" + "\n".join(
            f"  {f}: {m}" for f, m in violations[:10]
        )

    def test_before_starting_consistent(self, skill_files: list[Path]) -> None:
        """'Before Starting' 섹션이 있으면 일관된 형식이어야 함."""
        pattern = re.compile(r"^## Before Starting$", re.MULTILINE)

        files_with_before_starting = []
        for filepath in skill_files:
            # DEPRECATED 파일은 건너뜀
            if filepath.parent.name in DEPRECATED_SKILLS:
                continue

            try:
                content = filepath.read_text(encoding="utf-8")
                if pattern.search(content):
                    files_with_before_starting.append(filepath)
            except Exception:
                pass

        # 최소한 일부 파일은 Before Starting 섹션을 가지고 있어야 함
        assert len(files_with_before_starting) > 0, "Before Starting 섹션을 가진 파일이 없음"

    def test_yaml_frontmatter_unchanged(self, skill_files: list[Path]) -> None:
        """YAML frontmatter가 변경되지 않았는지 확인."""
        yaml_pattern = re.compile(r"^---\n.*?\n---", re.DOTALL)

        for filepath in skill_files[:10]:  # 처음 10개만 검사
            # DEPRECATED 파일은 건너뜀
            if filepath.parent.name in DEPRECATED_SKILLS:
                continue

            try:
                content = filepath.read_text(encoding="utf-8")
                if yaml_pattern.match(content):
                    # YAML frontmatter가 있으면 "시작 전 확인"이 없어야 함
                    assert (
                        "시작 전 확인" not in content.split("---\n", 2)[-1]
                    ), f"YAML frontmatter 내부에 '시작 전 확인' 있음: {filepath}"
            except Exception:
                pass

    def test_section_content_preserved(self, skill_files: list[Path]) -> None:
        """섹션 내용이 보존되었는지 확인."""
        pattern = re.compile(r"^## Before Starting\n(.+?)(?=^## |\Z)", re.MULTILINE | re.DOTALL)

        for filepath in skill_files[:10]:
            # DEPRECATED 파일은 건너뜀
            if filepath.parent.name in DEPRECATED_SKILLS:
                continue

            try:
                content = filepath.read_text(encoding="utf-8")
                match = pattern.search(content)
                if match:
                    section_content = match.group(1).strip()
                    # 섹션 내용이 비어있지 않아야 함
                    assert len(section_content) > 0, f"Before Starting 섹션이 비어있음: {filepath}"
            except Exception:
                pass


class TestChangeSummary:
    """변경 요약 테스트."""

    def test_change_count(self) -> None:
        """변경된 파일 수 확인."""
        # 이전에 변경 스크립트에서 23개 파일 변경됨
        expected_count = 23

        # 변경된 파일들이 Before Starting을 가지고 있는지 확인
        changed_files = [
            "onboarding-cro",
            "paid-ads",
            "analytics-tracking",
            "paywall-upgrade-cro",
            "cold-email",
            "competitor-alternatives",
            "copy-editing",
            "launch-strategy",
            "social-content",
            "free-tool-strategy",
            "lead-magnets",
            "popup-cro",
            "ad-creative",
            "site-architecture",
            "form-cro",
            "churn-prevention",
            "referral-program",
            "schema-markup",
            "ab-test-setup",
            "sales-enablement",
            "revops",
            "ai-seo",
            "email-sequence",
        ]

        assert len(changed_files) == expected_count, f"변경된 파일 수 불일치: {len(changed_files)} != {expected_count}"

        # 각 파일이 Before Starting 섹션을 가지고 있는지 확인
        for skill_name in changed_files:
            filepath = SKILLS_DIR / skill_name / "SKILL.md"
            if filepath.exists():
                content = filepath.read_text(encoding="utf-8")
                assert "## Before Starting" in content, f"Before Starting 섹션 없음: {skill_name}"


class TestIntegration:
    """통합 테스트."""

    def test_all_skill_md_files_valid(self) -> None:
        """모든 SKILL.md 파일이 유효한지 확인."""
        skill_files = list(SKILLS_DIR.glob("*/SKILL.md"))

        for filepath in skill_files:
            # DEPRECATED 파일은 건너뜀
            if filepath.parent.name in DEPRECATED_SKILLS:
                continue

            try:
                content = filepath.read_text(encoding="utf-8")
                # 파일이 비어있지 않아야 함
                assert len(content) > 0, f"빈 파일: {filepath}"
                # 최소한 하나의 섹션 헤더가 있어야 함
                assert re.search(r"^## ", content, re.MULTILINE), f"섹션 헤더 없음: {filepath}"
            except Exception as e:
                pytest.fail(f"유효하지 않은 파일 {filepath}: {e}")
