#!/usr/bin/env python3
"""
Generate an index of all notable entries in the data/notables directory.

This script scans all YAML files in births/ and events/ subdirectories,
extracts the names and categories, and generates a sorted index file.

Usage:
    python data/notables/generate_index.py

Output:
    data/notables/INDEX.md - Markdown file listing all notables by category
"""

from pathlib import Path

import yaml


def load_notables_from_file(filepath: Path) -> list[dict]:
    """Load notable entries from a YAML file."""
    with open(filepath) as f:
        data = yaml.safe_load(f)
    return data if data else []


def main():
    # Get the directory where this script lives
    script_dir = Path(__file__).parent

    # Collect all notables
    births = {}  # category -> list of names
    events = []

    # Scan births directory
    births_dir = script_dir / "births"
    if births_dir.exists():
        for yaml_file in sorted(births_dir.glob("*.yaml")):
            entries = load_notables_from_file(yaml_file)
            for entry in entries:
                name = entry.get("name", "Unknown")
                category = entry.get("category", "uncategorized")
                subcats = entry.get("subcategories", [])
                year = entry.get("year", "?")
                notable_for = entry.get("notable_for", "")

                if category not in births:
                    births[category] = []
                births[category].append(
                    {
                        "name": name,
                        "year": year,
                        "subcategories": subcats,
                        "notable_for": notable_for,
                        "source_file": yaml_file.name,
                    }
                )

    # Scan events directory
    events_dir = script_dir / "events"
    if events_dir.exists():
        for yaml_file in sorted(events_dir.glob("*.yaml")):
            entries = load_notables_from_file(yaml_file)
            for entry in entries:
                name = entry.get("name", "Unknown")
                year = entry.get("year", "?")
                notable_for = entry.get("notable_for", "")

                events.append(
                    {
                        "name": name,
                        "year": year,
                        "notable_for": notable_for,
                        "source_file": yaml_file.name,
                    }
                )

    # Generate the index markdown
    lines = [
        "# Stellium Notables Index",
        "",
        "This file is auto-generated by `generate_index.py`.",
        "",
        f"**Total entries:** {sum(len(v) for v in births.values()) + len(events)}",
        "",
    ]

    # Births section
    lines.append("## Births")
    lines.append("")

    for category in sorted(births.keys()):
        entries = births[category]
        lines.append(f"### {category.title()} ({len(entries)})")
        lines.append("")

        # Sort by name
        for entry in sorted(entries, key=lambda x: x["name"]):
            subcats = (
                ", ".join(entry["subcategories"]) if entry["subcategories"] else ""
            )
            subcat_str = f" ({subcats})" if subcats else ""
            lines.append(f"- **{entry['name']}** ({entry['year']}){subcat_str}")

        lines.append("")

    # Events section
    if events:
        lines.append("## Events")
        lines.append("")

        for entry in sorted(events, key=lambda x: x["name"]):
            lines.append(f"- **{entry['name']}** ({entry['year']})")

        lines.append("")

    # Write the index file
    index_path = script_dir / "INDEX.md"
    with open(index_path, "w") as f:
        f.write("\n".join(lines))

    print(f"Generated {index_path}")
    print(
        f"  Births: {sum(len(v) for v in births.values())} entries across {len(births)} categories"
    )
    print(f"  Events: {len(events)} entries")


if __name__ == "__main__":
    main()
