"""Typed helpers for {{ module_title }} metadata serialization."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Mapping, MutableMapping, Sequence


def _coerce_str(value: Any, default: str | None = None) -> str | None:
    if value is None:
        return default
    text = str(value).strip()
    return text or default


def _coerce_bool(value: Any, default: bool) -> bool:
    if isinstance(value, bool):
        return value
    if value is None:
        return default
    lowered = str(value).strip().lower()
    if lowered in {"1", "true", "yes", "on"}:
        return True
    if lowered in {"0", "false", "no", "off"}:
        return False
    return default


def _coerce_int(value: Any, default: int) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):  # pragma: no cover - defensive guard
        return default


def _coerce_sequence(value: Any) -> tuple[str, ...]:
    if value is None:
        return ()
    if isinstance(value, str):
        return tuple(item.strip() for item in value.split(",") if item.strip())
    if isinstance(value, Sequence):
        return tuple(str(item).strip() for item in value if str(item).strip())
    return ()


@dataclass(frozen=True)
class {{ module_class_name }}HealthSnapshot:
    """Normalized Users Core health payload."""

    module: str
    status: str
    checked_at: datetime
    allow_registration: bool
    enforce_unique_email: bool
    default_locale: str
    audit_log_enabled: bool
    max_results_per_page: int
    passwordless_supported: bool
    supported_locales: tuple[str, ...]
    features: tuple[str, ...]
    detail: str | None = None

    @classmethod
    def from_mapping(
        cls,
        payload: Mapping[str, Any],
        *,
        module_name: str,
        features: Sequence[str],
        detail: str | None = None,
    ) -> "{{ module_class_name }}HealthSnapshot":
        module = _coerce_str(payload.get("module"), module_name) or module_name
        status = _coerce_str(payload.get("status"), "unknown") or "unknown"
        checked_at_raw = payload.get("checked_at")
        if isinstance(checked_at_raw, datetime):
            checked_at = checked_at_raw
        elif checked_at_raw:
            try:
                checked_at = datetime.fromisoformat(str(checked_at_raw))
            except ValueError:  # pragma: no cover - defensive guard
                checked_at = datetime.now(timezone.utc)
        else:
            checked_at = datetime.now(timezone.utc)
        if checked_at.tzinfo is None:
            checked_at = checked_at.replace(tzinfo=timezone.utc)

        return cls(
            module=module,
            status=status,
            checked_at=checked_at,
            allow_registration=_coerce_bool(payload.get("allow_registration"), True),
            enforce_unique_email=_coerce_bool(payload.get("enforce_unique_email"), True),
            default_locale=_coerce_str(payload.get("default_locale"), "en") or "en",
            audit_log_enabled=_coerce_bool(payload.get("audit_log_enabled"), True),
            max_results_per_page=_coerce_int(payload.get("max_results_per_page"), 100),
            passwordless_supported=_coerce_bool(payload.get("passwordless_supported"), False),
            supported_locales=_coerce_sequence(payload.get("supported_locales")),
            features=tuple(str(feature) for feature in features if str(feature).strip()),
            detail=detail,
        )


def as_dict(snapshot: {{ module_class_name }}HealthSnapshot) -> MutableMapping[str, Any]:
    payload: MutableMapping[str, Any] = {
        "module": snapshot.module,
        "status": snapshot.status,
        "checked_at": snapshot.checked_at.isoformat(),
        "allow_registration": snapshot.allow_registration,
        "enforce_unique_email": snapshot.enforce_unique_email,
        "default_locale": snapshot.default_locale,
        "audit_log_enabled": snapshot.audit_log_enabled,
        "max_results_per_page": snapshot.max_results_per_page,
        "passwordless_supported": snapshot.passwordless_supported,
        "supported_locales": list(snapshot.supported_locales),
        "features": list(snapshot.features),
    }
    if snapshot.detail:
        payload["detail"] = snapshot.detail
    return payload


__all__ = [
    "{{ module_class_name }}HealthSnapshot",
    "as_dict",
]
