"""
Generate translation_catalog.py from pymissive.config.

Strings in pymissive.config (pymissive/config/__init__.py) are used via variables in
django_pymissive.models.choices, so xgettext (makemessages) cannot extract them.
This command generates a Python module with explicit _("literal") calls so makemessages
can find them.

Sources: MISSIVE_ACKNOWLEDGEMENT_LEVELS, MISSIVE_TYPES, SUCCESSFUL_EVENTS, INFO_EVENTS,
FAILED_EVENTS, DELIVERY_MODES, PRIORITIES, GENERIC_SUPPORT.

Run before makemessages:
  ./manage.py update_translation_catalog
  ./manage.py makemessages -l fr
"""

from pathlib import Path

from django.core.management.base import BaseCommand


def extract_strings_from_config() -> set[str]:
    """Extract all user-facing strings from pymissive.config."""
    from pymissive.config import (
        MISSIVE_ACKNOWLEDGEMENT_LEVELS,
        MISSIVE_TYPES,
        SUCCESSFUL_EVENTS,
        INFO_EVENTS,
        FAILED_EVENTS,
        DELIVERY_MODES,
        PRIORITIES,
        GENERIC_SUPPORT,
    )

    strings: set[str] = set()

    for level in MISSIVE_ACKNOWLEDGEMENT_LEVELS:
        strings.add(level["display_name"])
        if level.get("description"):
            strings.add(level["description"])
        if level.get("legal_value"):
            strings.add(level["legal_value"])
        for m in level.get("means") or []:
            strings.add(m)

    for v in MISSIVE_TYPES.values():
        strings.add(v)

    def _add_event_strings(events_dict):
        for v in events_dict.values():
            if isinstance(v, tuple):
                strings.add(v[0])
                if len(v) > 1 and v[1]:
                    strings.add(v[1])
            else:
                strings.add(v)

    _add_event_strings(SUCCESSFUL_EVENTS)
    _add_event_strings(INFO_EVENTS)
    _add_event_strings(FAILED_EVENTS)

    for k in DELIVERY_MODES:
        strings.add(k.capitalize())

    for k in PRIORITIES:
        strings.add(k.capitalize())

    for k in GENERIC_SUPPORT.keys():
        strings.add(k.capitalize())

    return strings


def generate_catalog_content(strings: set[str]) -> str:
    """Generate translation_catalog.py source."""
    sorted_strings = sorted(strings, key=lambda s: (s.lower(), s))

    lines = [
        '"""',
        "Translation catalog for pymissive.config strings.",
        "",
        "Auto-generated by: ./manage.py update_translation_catalog",
        "Do not edit manually. Run update_translation_catalog after config changes.",
        '"""',
        "",
        "from django.utils.translation import gettext_lazy as _",
        "",
        "# Strings from pymissive.config - used by makemessages for extraction",
        "",
    ]

    for s in sorted_strings:
        if not s or not isinstance(s, str):
            continue
        # Escape backslash and quote for Python string literal
        escaped = s.replace("\\", "\\\\").replace('"', '\\"')
        lines.append(f'_("{escaped}")')

    return "\n".join(lines) + "\n"


class Command(BaseCommand):
    help = "Generate translation_catalog.py from pymissive.config for makemessages extraction"

    def handle(self, *args, **options):
        strings = extract_strings_from_config()
        content = generate_catalog_content(strings)

        package_dir = Path(__file__).resolve().parent.parent.parent
        output_path = package_dir / "translation_catalog.py"

        output_path.write_text(content, encoding="utf-8")

        self.stdout.write(
            self.style.SUCCESS(
                f"Generated {output_path} with {len(strings)} translatable strings."
            )
        )
        self.stdout.write(
            "Run: ./manage.py makemessages -l fr"
        )
