import json
import pathlib
import re

# Configuration
SOURCE_FILE = "docs/AFO_ROYAL_LIBRARY.md"
DEST_FILE = "packages/dashboard/src/data/royal_rules.ts"


def parse_markdown(file_path) -> None:
    """
    Parses AFO_ROYAL_LIBRARY.md to extract 41 Rules.
    Returns a structured dictionary:
    {
        "books": [
            {
                "title": "I. 제1서: 손자병법",
                "rules": [
                    { "id": 1, "name": "지피지기", "principle": "...", "code": "..." }
                ]
            }
        ]
    }
    """
    content = pathlib.Path(file_path).read_text(encoding="utf-8")

    books = []

    # Split by Books (Header 2)
    book_sections = re.split(r"## ([IV]+)\. (.+)", content)

    # Skip intro (index 0)
    for i in range(1, len(book_sections), 3):
        book_num = book_sections[i]
        book_title = book_sections[i + 1].strip()
        book_content = book_sections[i + 2]

        rules = []

        # Regex for Rules: "1. **Title:**" ... "- **원칙**: ..." ... "- **코드**: ..."
        # Pattern handles multi-line content moderately well
        rule_pattern = re.compile(
            r"(\d+)\.\s+\*\*([^\)]+)\):\*\*\s+"
            r"-\s+\*\*원칙\*\*:\s+(.+?)\s+"
            r"-\s+\*\*코드\*\*:\s+(.+?)(?=\n\d+\.|\n\n|$)",
            re.DOTALL,
        )

        matches = rule_pattern.findall(book_content)

        for m in matches:
            rule_id = int(m[0])
            rule_name = m[1].strip()
            principle = m[2].strip()
            code_action = m[3].strip()

            rules.append(
                {
                    "id": rule_id,
                    "name": rule_name,
                    "principle": principle,
                    "code": code_action,
                }
            )

        books.append({"id": book_num, "title": f"{book_num}. {book_title}", "rules": rules})

    return books


def generate_typescript(books) -> None:
    """Generates the TypeScript content."""
    ts_content = "// AUTO-GENERATED BY scripts/sync_royal_library.py\n"
    ts_content += "// DO NOT EDIT DIRECTLY. EDIT docs/AFO_ROYAL_LIBRARY.md INSTEAD.\n\n"

    ts_content += "export interface RoyalRule {\n"
    ts_content += "  id: number;\n"
    ts_content += "  name: string;\n"
    ts_content += "  principle: string;\n"
    ts_content += "  code: string;\n"
    ts_content += "}\n\n"

    ts_content += "export interface RoyalBook {\n"
    ts_content += "  id: string;\n"
    ts_content += "  title: string;\n"
    ts_content += "  rules: RoyalRule[];\n"
    ts_content += "}\n\n"

    ts_content += "export const ROYAL_RULES: RoyalBook[] = "
    ts_content += json.dumps(books, indent=2, ensure_ascii=False)
    ts_content += ";\n"

    return ts_content


def main() -> None:
    print(f"📖 Reading from {SOURCE_FILE}...")
    if not pathlib.Path(SOURCE_FILE).exists():
        print("❌ Error: Source file not found.")
        return

    try:
        books = parse_markdown(SOURCE_FILE)
        print(f"✅ Parsed {len(books)} books.")
        for b in books:
            print(f"   - {b['title']}: {len(b['rules'])} rules")

        ts_content = generate_typescript(books)

        pathlib.Path(DEST_FILE).write_text(ts_content, encoding="utf-8")

        print(f"💾 Written to {DEST_FILE}")
        print("🔄 Sync Complete.")

    except Exception as e:
        print(f"❌ Error parsing markdown: {e}")


if __name__ == "__main__":
    main()
