"""What the organisation's plan allows in storage: one figure for vectors, one for cloud objects, for every
product together. Read by code off the platform's own records; a plan that names no figure sets no limit."""
from __future__ import annotations

import json
import re
from dataclasses import dataclass
from typing import Optional

VECTOR_KEY = "Vector_DB_Space"     # the plan feature; wherever it sits on the plan, it is the organisation's
CLOUD_KEY = "Cloud_Storage"        # the plan feature once the backend carries one; else Plans.storageAllocationMB (MB)
MB = 1024 * 1024
UNITS = {"KB": 1024, "MB": MB, "GB": 1024 * MB, "TB": 1024 * 1024 * MB}
UNIT_IN_VALUE = re.compile(r"^((?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?)\s*(KB|MB|GB|TB)?$", re.I)


@dataclass(frozen=True)
class StoragePlan:
    organisation_id: str
    plan_id: Optional[str]
    vector_bytes: Optional[int]    # None = no limit
    cloud_bytes: Optional[int]     # None = no limit


def _mb(value) -> Optional[int]:
    """A plan column in MB as bytes; 'unlimited', blank or unreadable means no limit."""
    text = str(value if value is not None else "").replace(",", "").strip()
    return int(text) * MB if text.isdigit() and int(text) > 0 else None


def _storage_bytes(value, unit=None) -> Optional[int]:
    """A storage figure as bytes, the way the platform writes it: the unit inside the value ("2GB", "512 MB",
    "1.5 TB") wins; else the feature's own allowanceUnit; else GB, the platform's default for a bare storage cap.
    'unlimited', blank or unreadable means no limit."""
    text = str(value if value is not None else "").strip()
    m = UNIT_IN_VALUE.match(text)
    if not m:
        return None
    amount = float(m.group(1).replace(",", ""))
    scale = UNITS.get((m.group(2) or unit or "GB").upper())
    if scale is None or amount <= 0:
        return None
    return int(amount * scale)


def feature_allowance(products, key: str) -> Optional[int]:
    """The plan's figure for `key`, as bytes, the way AI tokens are read: the add-on total (includedAllowanceTotal)
    wins when the backend wrote one; otherwise the first feature carrying the key. None when the plan says nothing."""
    products = json.loads(products) if isinstance(products, str) else (products or [])
    features = [f for p in products if isinstance(p, dict) for f in (p.get("features") or [])
                if isinstance(f, dict) and f.get("featureKey") == key and f.get("enabled") is not False]
    for f in features:
        total = _storage_bytes(f.get("includedAllowanceTotal"), f.get("allowanceUnit"))
        if total is not None:
            return total
    for f in features:
        given = _storage_bytes(f.get("cappingValue"), f.get("allowanceUnit"))
        if given is not None:
            return given
    return None


def vector_allowance(products) -> Optional[int]:
    return feature_allowance(products, VECTOR_KEY)


def cloud_allowance(products, column_mb) -> Optional[int]:
    """The Cloud_Storage feature when the plan carries one (the add-on path, same as tokens); until then the
    plan's storageAllocationMB column."""
    from_feature = feature_allowance(products, CLOUD_KEY)
    return from_feature if from_feature is not None else _mb(column_mb)


def read_storage_plan(conn, tenant_id: str) -> Optional[StoragePlan]:
    """The organisation behind this tenant and what its newest live plan allows. None without a subscription."""
    rows = conn.execute(
        'SELECT o.id AS org, p.id AS plan, p."productFeatures" AS features, p."storageAllocationMB" AS cloud_mb '
        '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, plan, features, cloud_mb = rows[0]
    return StoragePlan(str(org), str(plan) if plan else None, vector_allowance(features), cloud_allowance(features, cloud_mb))
