"""Generate constants.py and README.md from downloaded icon data."""
from __future__ import annotations

import logging
from datetime import datetime
from pathlib import Path

from .models import IconCategories, IconCodepoints

logger = logging.getLogger(__name__)


def generate_constants_file(
    output_dir: Path,
    icons_data: IconCodepoints,
    categories: IconCategories,
) -> None:
    """Write constants.py with Icons class and IconCategories to output_dir."""
    logger.info("📝 Generating constants.py...")
    sorted_icons = sorted(icons_data)

    lines: list[str] = [
        '"""',
        "Material Icons constants for IDE autocompletion.",
        "",
        "This file is auto-generated by generate_icons.py script.",
        "DO NOT EDIT MANUALLY - run the script to update.",
        "",
        "Generated from Google Material Design Icons.",
        f"Total icons: {len(sorted_icons)}",
        '"""',
        "",
        "from typing import Dict, Final",
        "",
        "",
        "class Icons:",
        '    """',
        "    Material Design Icons constants for IDE autocompletion.",
        "",
        "    Usage::",
        "",
        "        from django_cfg.modules.django_admin.icons import Icons",
        "",
        "        icon = Icons.DASHBOARD",
        "        icon = Icons.SETTINGS",
        '    """',
        "",
    ]

    for name in sorted_icons:
        const = _to_const(name)
        lines.append(f'    {const}: Final[str] = "{name}"')

    lines += [
        "",
        "    # Common aliases",
        "    USERS = PEOPLE",
        "    USER = PERSON",
        "    DOCUMENTS = DESCRIPTION",
        "    FILES = INSERT_DRIVE_FILE",
        "    FOLDERS = FOLDER",
        "    MESSAGES = MESSAGE",
        "    EMAILS = EMAIL",
        "    TASKS = QUEUE",
        "    AGENTS = SMART_TOY",
        "    AI = SMART_TOY",
        "",
        "",
        "# IDE-friendly icon categories",
        "class IconCategories:",
        '    """Categorized icon collections for easy discovery."""',
        "",
    ]

    for category, icons in categories.items():
        lines.append(f"    {category.upper()}: Dict[str, str] = {{")
        for icon in icons[:20]:
            lines.append(f"        '{icon}': Icons.{_to_const(icon)},")
        lines.append("    }")
        lines.append("")

    lines += [
        "",
        "__all__ = ['Icons', 'IconCategories']",
        "",
    ]

    (output_dir / "constants.py").write_text("\n".join(lines), encoding="utf-8")
    logger.info("✅ Generated constants.py with %d icons", len(sorted_icons))


def generate_readme(
    output_dir: Path,
    icons_data: IconCodepoints,
    categories: IconCategories,
) -> None:
    """Write README.md to output_dir."""
    logger.info("📝 Generating README.md...")

    categories_list = "\n".join(
        f"- **{cat.title()}** ({len(icons)} icons): "
        + ", ".join(icons[:5])
        + (f", ... (+{len(icons) - 5} more)" if len(icons) > 5 else "")
        for cat, icons in categories.items()
    )

    content = f"""# Material Icons for Django CFG

{len(icons_data)} icons · {len(categories)} categories · auto-generated

## Usage

```python
from django_cfg.modules.django_admin.icons import Icons

icon = Icons.DASHBOARD   # IDE autocompletion
```

## Updating

```bash
python generate_icons.py
```

## Categories

{categories_list}

---
*Last updated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}*
"""

    (output_dir / "README.md").write_text(content, encoding="utf-8")
    logger.info("✅ Generated README.md")


def _to_const(name: str) -> str:
    """Convert an icon name to a valid Python constant identifier."""
    const = name.upper().replace("-", "_")
    return f"_{const}" if const[0].isdigit() else const
