"""Default template loader — reads .jinja2 files for seeding into DB."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Any

_LOGGER = logging.getLogger(__name__)

_DEFAULTS_DIR = Path(__file__).parent

# Per-provider mapping of template slot names to file names
PROVIDER_SLOT_FILE_MAP: dict[str, dict[str, str]] = {
    "immich": {
        "message_assets_added": "assets_added.jinja2",
        "message_assets_removed": "assets_removed.jinja2",
        "message_collection_renamed": "collection_renamed.jinja2",
        "message_collection_deleted": "collection_deleted.jinja2",
        "message_sharing_changed": "sharing_changed.jinja2",
        "periodic_summary_message": "periodic_summary.jinja2",
        "scheduled_assets_message": "scheduled_assets.jinja2",
        "memory_mode_message": "memory_mode.jinja2",
    },
    "gitea": {
        "message_push": "gitea_push.jinja2",
        "message_issue_opened": "gitea_issue_opened.jinja2",
        "message_issue_closed": "gitea_issue_closed.jinja2",
        "message_issue_commented": "gitea_issue_commented.jinja2",
        "message_pr_opened": "gitea_pr_opened.jinja2",
        "message_pr_closed": "gitea_pr_closed.jinja2",
        "message_pr_merged": "gitea_pr_merged.jinja2",
        "message_pr_commented": "gitea_pr_commented.jinja2",
        "message_release_published": "gitea_release_published.jinja2",
    },
    "planka": {
        "message_card_created": "planka_card_created.jinja2",
        "message_card_updated": "planka_card_updated.jinja2",
        "message_card_moved": "planka_card_moved.jinja2",
        "message_card_deleted": "planka_card_deleted.jinja2",
        "message_card_commented": "planka_card_commented.jinja2",
        "message_comment_updated": "planka_comment_updated.jinja2",
        "message_board_created": "planka_board_created.jinja2",
        "message_board_updated": "planka_board_updated.jinja2",
        "message_board_deleted": "planka_board_deleted.jinja2",
        "message_list_created": "planka_list_created.jinja2",
        "message_list_updated": "planka_list_updated.jinja2",
        "message_list_deleted": "planka_list_deleted.jinja2",
        "message_attachment_created": "planka_attachment_created.jinja2",
        "message_card_label_added": "planka_card_label_added.jinja2",
        "message_task_completed": "planka_task_completed.jinja2",
    },
    "scheduler": {
        "message_scheduled_message": "scheduled_message.jinja2",
    },
    "google_photos": {
        "message_assets_added": "gp_assets_added.jinja2",
        "message_assets_removed": "gp_assets_removed.jinja2",
        "message_collection_renamed": "gp_collection_renamed.jinja2",
        "message_collection_deleted": "gp_collection_deleted.jinja2",
        "message_sharing_changed": "gp_sharing_changed.jinja2",
    },
    "webhook": {
        "message_webhook_received": "webhook_received.jinja2",
    },
    "nut": {
        "message_ups_online": "nut_ups_online.jinja2",
        "message_ups_on_battery": "nut_ups_on_battery.jinja2",
        "message_ups_low_battery": "nut_ups_low_battery.jinja2",
        "message_ups_battery_restored": "nut_ups_battery_restored.jinja2",
        "message_ups_comms_lost": "nut_ups_comms_lost.jinja2",
        "message_ups_comms_restored": "nut_ups_comms_restored.jinja2",
        "message_ups_replace_battery": "nut_ups_replace_battery.jinja2",
        "message_ups_overload": "nut_ups_overload.jinja2",
    },
    "home_assistant": {
        "message_ha_state_changed": "ha_state_changed.jinja2",
        "message_ha_automation_triggered": "ha_automation_triggered.jinja2",
        "message_ha_service_called": "ha_service_called.jinja2",
        "message_ha_event_fired": "ha_event_fired.jinja2",
    },
    "bridge_self": {
        "message_bridge_self_poll_failures": "bridge_self_poll_failures.jinja2",
        "message_bridge_self_deferred_backlog": "bridge_self_deferred_backlog.jinja2",
        "message_bridge_self_target_failures": "bridge_self_target_failures.jinja2",
    },
}

# Backward-compatible alias
SLOT_FILE_MAP: dict[str, str] = PROVIDER_SLOT_FILE_MAP["immich"]


def load_default_templates(
    locale: str = "en",
    provider_type: str = "immich",
) -> dict[str, str]:
    """Load default template strings for a locale and provider type.

    Args:
        locale: "en" or "ru"
        provider_type: "immich" or "gitea"

    Returns:
        Dict mapping slot name -> template string content.
    """
    locale_dir = _DEFAULTS_DIR / locale
    if not locale_dir.is_dir():
        _LOGGER.warning("No default templates for locale '%s'", locale)
        return {}

    slot_map = PROVIDER_SLOT_FILE_MAP.get(provider_type, {})
    templates: dict[str, str] = {}
    for slot_name, filename in slot_map.items():
        filepath = locale_dir / filename
        if filepath.exists():
            templates[slot_name] = filepath.read_text(encoding="utf-8").strip()
        else:
            _LOGGER.debug("Missing default template: %s/%s", locale, filename)

    return templates


def get_available_locales() -> list[str]:
    """Return list of available locale codes."""
    locales = []
    for path in _DEFAULTS_DIR.iterdir():
        if path.is_dir() and not path.name.startswith("_"):
            locales.append(path.name)
    return sorted(locales)
