#!/usr/bin/env python3
"""task-1058.1: Before Starting 명칭 통일 스크립트

모든 SKILL.md 파일에서 "시작 전 확인" 관련 섹션 헤더를 "Before Starting"으로 통일.
"""

import re
from pathlib import Path

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

# 변경 패턴
PATTERNS = [
    (r"^## 시작 전 확인사항$", "## Before Starting"),
    (r"^## 시작 전 확인$", "## Before Starting"),
]


def find_skill_files():
    """SKILL.md 파일 목록 반환."""
    return list(SKILLS_DIR.glob("*/SKILL.md"))


def check_needs_change(filepath: Path) -> list[tuple[int, str, str]]:
    """변경이 필요한 라인 반환 [(line_no, old_text, new_text), ...]"""
    changes = []
    try:
        lines = filepath.read_text(encoding="utf-8").split("\n")
        for i, line in enumerate(lines, 1):
            for pattern, replacement in PATTERNS:
                if re.match(pattern, line):
                    changes.append((i, line, replacement))
                    break
    except Exception as e:
        print(f"Error reading {filepath}: {e}")
    return changes


def apply_changes(filepath: Path, changes: list[tuple[int, str, str]]) -> bool:
    """변경 적용."""
    if not changes:
        return False

    try:
        lines = filepath.read_text(encoding="utf-8").split("\n")
        for line_no, old_text, new_text in changes:
            lines[line_no - 1] = new_text

        filepath.write_text("\n".join(lines), encoding="utf-8")
        return True
    except Exception as e:
        print(f"Error writing {filepath}: {e}")
        return False


def main():
    """메인 함수."""
    skill_files = find_skill_files()
    print(f"Found {len(skill_files)} SKILL.md files\n")

    all_changes = {}

    # 변경 필요한 파일 찾기
    for filepath in skill_files:
        changes = check_needs_change(filepath)
        if changes:
            all_changes[filepath] = changes

    print(f"Files needing changes: {len(all_changes)}\n")

    # 변경 적용
    for filepath, changes in all_changes.items():
        relative_path = filepath.relative_to(SKILLS_DIR.parent)
        print(f"\n{relative_path}:")
        for line_no, old_text, new_text in changes:
            print(f"  Line {line_no}:")
            print(f"    - {old_text}")
            print(f"    + {new_text}")

        if apply_changes(filepath, changes):
            print(f"  ✅ Applied")
        else:
            print(f"  ❌ Failed")

    # 요약
    print(f"\n{'='*60}")
    print(f"Summary:")
    print(f"  Total files scanned: {len(skill_files)}")
    print(f"  Files changed: {len(all_changes)}")
    print(f"  Total lines changed: {sum(len(c) for c in all_changes.values())}")

    return all_changes


if __name__ == "__main__":
    main()
