"""What an organisation may spend this period, read from the platform's own records.

The subscription's snapshot (featureConfiguration, written at checkout) is the truth when it exists; the plan's
productFeatures when it does not. Effective AI capacity includes purchased recurring packs;
per-product token features are not read. The period is the subscription's; a yearly subscription gets monthly windows from its anchor.
"""
from __future__ import annotations

import calendar
import json
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional

log = logging.getLogger("galaxiq.ai_credits")

AI_KEY = "AI_Tokens"   # the platform's AI token feature; per-product token features are not read


@dataclass(frozen=True)
class Entitlement:
    organisation_id: str
    subscription_id: Optional[str]
    start: datetime
    end: datetime
    allowance: int          # customer tokens for the period, pooled across products; 0 when the plan gives none


def _aware(d: Optional[datetime]) -> Optional[datetime]:
    return d if d is None or d.tzinfo else d.replace(tzinfo=timezone.utc)


def add_months(day: datetime, months: int) -> datetime:
    year, month = divmod(day.year * 12 + day.month - 1 + months, 12)
    return day.replace(year=year, month=month + 1, day=min(day.day, calendar.monthrange(year, month + 1)[1]))


def anniversary_window(anchor: datetime, now: datetime) -> tuple:
    months = (now.year - anchor.year) * 12 + now.month - anchor.month
    if add_months(anchor, months) > now:
        months -= 1
    return add_months(anchor, months), add_months(anchor, months + 1)


def usage_window(start: Optional[datetime], end: Optional[datetime], created: Optional[datetime],
                 snapshot: Optional[dict], now: datetime) -> tuple:
    """The same window the platform backend uses (subscriptionUsageService.usageWindow)."""
    start, end, created = _aware(start), _aware(end), _aware(created)
    if snapshot and snapshot.get("billingCycle") == "yearly":
        anchor_text = snapshot.get("allowanceAnchor")
        anchor = _aware(datetime.fromisoformat(anchor_text.replace("Z", "+00:00"))) if anchor_text else start
        window_start, window_end = anniversary_window(anchor or now, now)
        if end and window_end > end:
            window_end = end
        return window_start, window_end
    if start and end and start <= now < end:
        return start, end
    return anniversary_window(created or now, now)


def _whole(value) -> Optional[int]:
    text = str(value if value is not None else "").replace(",", "").strip()
    return int(text) if text.isdigit() else None


def ai_allowance(products) -> Optional[int]:
    """One platform allowance, never the sum of repeated product mappings.

    Plan-scope rows are authoritative. Legacy product rows can carry the same
    shared included total beside smaller per-product caps; preserve that floor,
    but never add those rows or their recurring quantities together.
    """
    products = json.loads(products) if isinstance(products, str) else (products or [])
    values, plan_values = [], []
    for block in products:
        if not isinstance(block, dict):
            continue
        plan_scope = block.get("featureScope") == "plan"
        for feature in block.get("features") or []:
            if not isinstance(feature, dict) or feature.get("featureKey") != AI_KEY:
                continue
            if feature.get("enabled") is False:
                if plan_scope:
                    plan_values.append(0)
                continue
            effective = _whole(feature.get("effectiveAllowanceTotal"))
            cap = _whole(feature.get("cappingValue"))
            config = feature.get("aiTokenConfiguration")
            share = _whole(config.get("AI_Token")) if isinstance(config, dict) else None
            base = _whole(feature.get("includedAllowanceTotal"))
            if effective is None and str(feature.get("cappingValue", "")).strip().lower() in ("unlimited", "-1"):
                (plan_values if plan_scope else values).append(None)
                continue
            # Bare legacy product caps have no platform entitlement provenance.
            if not plan_scope and effective is None and share is None and base is None:
                continue
            value = next((v for v in (effective, cap, share, base) if v is not None), None)
            if value is None:
                continue
            if plan_scope:
                plan_values.append(value)
            else:
                # Explicit effective totals and zero are authoritative. Only
                # legacy shared-base metadata supplies a floor for product shares.
                if effective is None and value > 0 and base is not None:
                    value = max(value, base)
                values.append(value)
    selected = plan_values if plan_values else values
    if not selected or None in selected:
        return None
    if len(set(selected)) > 1:
        log.warning("ai credits: conflicting platform AI totals %s; using largest, not their sum", selected)
    return max(selected)


def read_entitlement(conn, tenant_id: str, now: Optional[datetime] = None) -> Optional[Entitlement]:
    """The organisation behind this tenant and what its newest live subscription allows. None without one."""
    now = now or datetime.now(timezone.utc)
    rows = conn.execute(
        'SELECT o.id AS org, s.id AS sub, s."currentPeriodStart" AS starts, s."currentPeriodEnd" AS ends, '
        '       s."createdAt" AS created, p."productFeatures" AS plan_features '
        'FROM "Organisations" o '
        'JOIN "Subscriptions" s ON s."organisationId" = o.id '
        'LEFT JOIN "Plans" p ON p.id = s."planId" '
        'WHERE o."tenantId"::text = %s '
        "  AND (s.\"isActive\" = TRUE OR lower(coalesce(s.status, '')) IN ('active', 'trial', 'trialing') "
        '       OR (s."trialStart" IS NOT NULL AND s."trialEnd" IS NOT NULL AND now() BETWEEN s."trialStart" AND s."trialEnd")) '
        'ORDER BY s."createdAt" DESC NULLS LAST',
        (str(tenant_id).removeprefix("org_"),)).fetchall()
    if not rows:
        return None
    org, sub, starts, ends, created, plan_features = rows[0]
    snapshot = _snapshot(conn, sub)
    products = snapshot.get("productFeatures") if snapshot and snapshot.get("active") is True else plan_features
    start, end = usage_window(starts, ends, created, snapshot, now)
    return Entitlement(str(org), str(sub) if sub else None, start, end, ai_allowance(products) or 0)


def _snapshot(conn, subscription_id) -> Optional[dict]:
    """The checkout snapshot, when the platform has that column (it does not yet on every environment)."""
    has = conn.execute("SELECT 1 FROM information_schema.columns WHERE table_name = 'Subscriptions' "
                       "AND column_name = 'featureConfiguration'").fetchone()
    if not has:
        return None
    row = conn.execute('SELECT "featureConfiguration" FROM "Subscriptions" WHERE id = %s', (subscription_id,)).fetchone()
    value = row[0] if row else None
    return json.loads(value) if isinstance(value, str) else value
