"""Typed helpers for Passwordless module metadata serialization."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping, MutableMapping


@dataclass(frozen=True)
class PasswordlessHealthSnapshot:
    """Normalized snapshot consumed by passwordless health endpoints."""

    module: str
    token_ttl_seconds: int
    token_length: int
    resend_cooldown_seconds: int
    max_attempts: int
    delivery_methods: tuple[str, ...]
    magic_link_base_url: str
    supports_magic_links: bool
    supports_codes: bool
    features: tuple[str, ...]

    @classmethod
    def from_mapping(cls, data: Mapping[str, Any]) -> "PasswordlessHealthSnapshot":
        delivery = tuple(
            str(method).lower()
            for method in data.get("delivery_methods", [])
            if isinstance(method, str) and method
        )
        features = tuple(
            str(feature)
            for feature in data.get("features", [])
            if isinstance(feature, str) and feature
        )
        return cls(
            module=str(data.get("module", "passwordless")),
            token_ttl_seconds=int(data.get("token_ttl_seconds", 0)),
            token_length=int(data.get("token_length", 0)),
            resend_cooldown_seconds=int(data.get("resend_cooldown_seconds", 0)),
            max_attempts=int(data.get("max_attempts", 0)),
            delivery_methods=delivery,
            magic_link_base_url=str(data.get("magic_link_base_url", "")),
            supports_magic_links=bool(data.get("supports_magic_links", True)),
            supports_codes=bool(data.get("supports_codes", True)),
            features=features,
        )


def as_dict(snapshot: PasswordlessHealthSnapshot) -> MutableMapping[str, Any]:
    """Render the snapshot into a JSON-serializable mapping."""

    return {
        "module": snapshot.module,
        "token_ttl_seconds": snapshot.token_ttl_seconds,
        "token_length": snapshot.token_length,
        "resend_cooldown_seconds": snapshot.resend_cooldown_seconds,
        "max_attempts": snapshot.max_attempts,
        "delivery_methods": list(snapshot.delivery_methods),
        "magic_link_base_url": snapshot.magic_link_base_url,
        "supports_magic_links": snapshot.supports_magic_links,
        "supports_codes": snapshot.supports_codes,
        "features": list(snapshot.features),
    }


__all__ = ["PasswordlessHealthSnapshot", "as_dict"]
