"""Billing notification templates - centralized subject/body construction."""
from __future__ import annotations
from typing import Tuple


def _transactional(
    *,
    subject: str,
    title: str,
    intro: str,
    action_label: str | None = None,
    action_url: str | None = None,
    details: tuple[tuple[str, str], ...] = (),
    note: str | None = None,
) -> Tuple[str, str]:
    """Render billing notifications through the shared presentation system."""
    from src.domain.email.presentation import (
        ApplicationBranding,
        EmailMessage,
        EmailPresentation,
        render_transactional_email,
    )

    message = EmailMessage(
        recipient="",
        branding=ApplicationBranding("P2HS"),
        presentation=EmailPresentation(
            template_key="billing.notification",
            template_version="billing.notification.v1",
            title=title,
            intro=intro,
            action_label=action_label,
            action_url=action_url,
            fallback_url=action_url,
            details=details,
            note=note,
        ),
        subject=subject,
    )
    html, text = render_transactional_email(message)
    return text, html


def format_amount(minor: int, currency: str = "usd") -> str:
    """Format amount for display."""
    if currency == "usd":
        return f"${minor / 100:.2f}"
    return f"{minor / 100} {currency.upper()}"


def invoice_paid_subject(amount_minor: int, currency: str = "usd") -> str:
    return f"Invoice paid - {format_amount(amount_minor, currency)}"


def invoice_paid_body(invoice_url: str, amount_minor: int, currency: str = "usd") -> Tuple[str, str]:
    amount_str = format_amount(amount_minor, currency)
    return _transactional(subject=invoice_paid_subject(amount_minor, currency), title="Invoice paid", intro="Your P2HS invoice has been paid.", action_label="View invoice" if invoice_url else None, action_url=invoice_url or None, details=(("Amount", amount_str),))


def payment_failed_subject() -> str:
    return "Payment failed - P2HS"


def payment_failed_body(invoice_url: str) -> Tuple[str, str]:
    return _transactional(subject=payment_failed_subject(), title="Payment failed", intro="Your P2HS payment could not be processed. Please update your payment method.", action_label="View invoice" if invoice_url else None, action_url=invoice_url or None)


def subscription_canceled_subject(plan_slug: str) -> str:
    return f"Subscription canceled - {plan_slug}"


def subscription_canceled_body(plan_slug: str, period_end_iso: str) -> Tuple[str, str]:
    return _transactional(subject=subscription_canceled_subject(plan_slug), title="Subscription canceled", intro=f"Your {plan_slug} subscription will end on {period_end_iso}.", note="You will retain access until then.")


def wallet_threshold_subject(wallet_type: str, pct: int) -> str:
    label = "Codegen" if wallet_type == "codegen" else "Cloud"
    if pct >= 100:
        return f"{label} credits exhausted"
    return f"{label} credits {pct}% consumed"


def wallet_threshold_body(wallet_type: str, pct: int, credits_used: float) -> Tuple[str, str]:
    label = "codegen" if wallet_type == "codegen" else "Cloud"
    if pct >= 100:
        if wallet_type == "codegen":
            text = (
                f"Your workspace has used all available {label} credits ({credits_used:.0f} used). "
                "Purchase a codegen top-up to continue building."
            )
        else:
            text = (
                f"Your workspace has used all available {label} credits ({credits_used:.2f} used). "
                "The public web app is unavailable until you add Cloud credits. "
                "If you are the owner of the site please contact support or top up from Billing."
            )
    else:
        text = (
            f"Your workspace has consumed {pct}% of its {label} credits ({credits_used:.2f} used). "
            "Review usage and top up from Billing if you need more."
        )
    return _transactional(subject=wallet_threshold_subject(wallet_type, pct), title=wallet_threshold_subject(wallet_type, pct), intro=text, action_label="Open billing", action_url="/billing")


def usage_topup_confirmation_subject(package_name: str) -> str:
    return f"Usage credits purchased - {package_name}"


def usage_topup_confirmation_body(package_name: str, units: int, amount_minor: int, currency: str = "usd") -> Tuple[str, str]:
    amount_str = format_amount(amount_minor, currency)
    return _transactional(subject=usage_topup_confirmation_subject(package_name), title="Usage credits purchased", intro=f"You purchased {units} usage credits ({package_name}) for {amount_str}.", note="They have been added to your workspace.")
