"""Single source of truth for billing status normalization (DB / Stripe statuses)."""
from __future__ import annotations

from typing import Any, Optional

from src.domain.billing.constants import FREE_PLAN_SLUG, STAFF_PLAN_SLUG
from src.domain.billing.enums import BillingStatus

_NO_CHARGE_SLUGS = frozenset({FREE_PLAN_SLUG, STAFF_PLAN_SLUG})


def normalized_billing_status_from_row(sub: Optional[Any], selected_plan_slug: Optional[str] = None) -> str:
    """Map latest subscription row to API billing.status.

    No subscription + no-charge plan (free/staff) → active (subscribed, just not billed).
    No subscription + no plan → none.
    """
    if not sub:
        if (selected_plan_slug or "").lower() in _NO_CHARGE_SLUGS:
            return BillingStatus.ACTIVE.value
        return BillingStatus.NONE.value
    st = getattr(sub, "status", None) or BillingStatus.NONE.value
    return str(st).lower()


def is_payable_plan(plan_slug: Optional[str]) -> bool:
    """True if the plan routes through Stripe (money is involved)."""
    return (plan_slug or "").lower() not in _NO_CHARGE_SLUGS


def is_paid_billing_status(status: str) -> bool:
    return status in (BillingStatus.ACTIVE.value, BillingStatus.TRIALING.value)


def requires_payment_flag(billing_status: str, selected_plan_slug: Optional[str]) -> bool:
    """True while workspace still needs payment or billing resolution (not active/trialing)."""
    if is_paid_billing_status(billing_status):
        return False
    if billing_status == BillingStatus.COMPLIMENTARY.value:
        return False
    if billing_status in (
        BillingStatus.PAST_DUE.value,
        BillingStatus.INCOMPLETE.value,
        BillingStatus.CANCELED.value,
        BillingStatus.UNPAID.value,
    ):
        return True
    if billing_status == BillingStatus.NONE.value:
        return (selected_plan_slug or "").lower() not in _NO_CHARGE_SLUGS
    return True


def requires_plan_selection_flag(billing_status: str, selected_plan_slug: Optional[str]) -> bool:
    """User chose a paid plan but has not completed checkout yet."""
    if billing_status not in (BillingStatus.NONE.value, BillingStatus.COMPLIMENTARY.value):
        return False
    if billing_status == BillingStatus.COMPLIMENTARY.value:
        return False
    slug = (selected_plan_slug or "").lower()
    return bool(slug) and slug not in _NO_CHARGE_SLUGS


def subscription_row_to_checkout_poll_status(
    *,
    sub: Optional[Any],
    billing_last_checkout_return: Optional[str],
    checkout_return_query: Optional[str],
) -> tuple[str, bool, bool]:
    """
    Returns (api_status, is_paid, has_subscription_row).

    api_status uses BillingStatus.VERIFYING when user landed from Stripe success but not yet paid in DB.
    """
    has_sub = sub is not None
    raw = normalized_billing_status_from_row(sub)
    paid = is_paid_billing_status(raw)

    ret = checkout_return_query or billing_last_checkout_return
    success_signal = ret == "success_return"

    if paid:
        return raw, True, has_sub
    if success_signal and not paid:
        return BillingStatus.VERIFYING.value, False, has_sub
    if not has_sub:
        return BillingStatus.NONE.value, False, False
    return raw, False, has_sub
