from __future__ import annotations

"""Explanations resource — customer explanation generation via the Nexure API."""

from typing import Any

from nexure.models import (
    ExplanationInfo,
    ExplanationListResult,
    ExplanationTemplateDetail,
    ExplanationTemplateInfo,
    ExplanationTemplateList,
    PortalExplanation,
    PortalLink,
)
from nexure.resources._base import BaseResource


class ExplanationsResource(BaseResource):
    """nx.explanations — customer explanation generation and management."""

    # ── Templates ──────────────────────────────────────────────

    def list_templates(
        self,
        *,
        decision_type: str | None = None,
        template_type: str | None = None,
    ) -> ExplanationTemplateList:
        """List explanation templates.

        Args:
            decision_type: Filter by decision type.
            template_type: Filter by type (adverse_action, approval, summary).
        """
        params: dict[str, Any] = {}
        if decision_type is not None:
            params["decision_type"] = decision_type
        if template_type is not None:
            params["template_type"] = template_type
        data = self._get("/explanation-templates", params=params or None)
        return ExplanationTemplateList(**data)

    def create_template(self, **kwargs: Any) -> ExplanationTemplateInfo:
        """Create an explanation template.

        Args:
            **kwargs: Template fields (name, decision_type,
                template_type, header_template, etc.).
        """
        data = self._post("/explanation-templates", json=kwargs)
        return ExplanationTemplateInfo(**data)

    def get_template(self, template_id: str) -> ExplanationTemplateDetail:
        """Get full explanation template detail."""
        data = self._get(f"/explanation-templates/{template_id}")
        return ExplanationTemplateDetail(**data)

    def update_template(self, template_id: str, **kwargs: Any) -> ExplanationTemplateInfo:
        """Update an explanation template."""
        data = self._put(f"/explanation-templates/{template_id}", json=kwargs)
        return ExplanationTemplateInfo(**data)

    def delete_template(self, template_id: str) -> None:
        """Delete an explanation template."""
        self._delete(f"/explanation-templates/{template_id}")

    # ── Explanations ───────────────────────────────────────────

    def generate(
        self,
        decision_id: str,
        *,
        template_id: str | None = None,
        language: str = "en",
    ) -> ExplanationInfo:
        """Generate a customer-facing explanation for a decision.

        Args:
            decision_id: The decision to explain.
            template_id: Specific template to use (auto-selects if None).
            language: Language code (default "en").
        """
        payload: dict[str, Any] = {"language": language}
        if template_id is not None:
            payload["template_id"] = template_id
        data = self._post(f"/decisions/{decision_id}/explanation", json=payload)
        return ExplanationInfo(**data)

    def list(self, decision_id: str) -> ExplanationListResult:
        """List all explanations for a decision."""
        data = self._get(f"/decisions/{decision_id}/explanations")
        return ExplanationListResult(**data)

    def portal_link(
        self,
        decision_id: str,
        explanation_id: str,
        *,
        expires_hours: int = 72,
    ) -> PortalLink:
        """Generate a portal access link for a customer.

        Args:
            decision_id: The decision ID.
            explanation_id: The explanation to make accessible.
            expires_hours: Hours until the link expires (1-720).
        """
        data = self._post(
            f"/decisions/{decision_id}/explanation/portal-link",
            json={
                "explanation_id": explanation_id,
                "expires_hours": expires_hours,
            },
        )
        return PortalLink(**data)

    def portal_view(self, token: str) -> PortalExplanation:
        """View an explanation via portal token (public).

        Args:
            token: The portal access token.
        """
        data = self._get(f"/portal/explanation/{token}")
        return PortalExplanation(**data)
