"""The one object a product holds for storage. Platform level: one vector allowance and one cloud allowance per
organisation, for every product together, read off the plan; usage measured in the organisation's schema.

    storage.check(tenant, "cloud", bytes_about_to_write)   raises StorageFull with the owner's sentence
    storage.record_object(tenant, kind, container, path, bytes, content_type)   after a blob is written
    storage.forget_object(tenant, container, path)                            after a blob is deleted
    storage.summary(tenant)                                                   both meters, for a screen

Fails open: when a database cannot be reached the write goes ahead and one line is logged. A billing fault must
not stop a campaign; only storage known to be full does. The owners are told in the platform bell at 80 and
100 percent of either allowance, once per crossing.
"""
from __future__ import annotations

import json
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional, Set

import psycopg

from ..ai_credits.client import org_schema
from ..ai_credits.notices import tell_members
from .measure import cloud_by_product, cloud_bytes, vector_bytes, vector_tables
from .plan import MB, StoragePlan, read_storage_plan

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

SQL = Path(__file__).resolve().parent / "sql" / "storage.sql"
KINDS = ("vector", "cloud")
MARKS = (80, 100)
_ensured: Set[str] = set()


class StorageFull(Exception):
    """The organisation's allowance cannot hold what is about to be written."""

    def __init__(self, kind: str, used: int, limit: int):
        what = "vector storage" if kind == "vector" else "storage"
        super().__init__(f"Your {what} is full ({used // MB:,} of {limit // MB:,} MB). "
                         "Remove what you no longer need, or move to a larger plan.")
        self.kind, self.used, self.limit = kind, used, limit


@dataclass(frozen=True)
class Decision:
    allowed: bool
    reason: str = ""            # "" | full | no_limit | no_subscription | unverified
    used: int = 0
    limit: Optional[int] = None

    def __bool__(self) -> bool:
        return self.allowed


def ensure_storage_tables(conn, schema: str) -> None:
    if schema in _ensured:
        return
    if not schema.replace("_", "").replace("-", "").isalnum():
        raise ValueError(f"not a schema name: {schema!r}")
    with conn.transaction():
        conn.execute(SQL.read_text(encoding="utf-8").replace("{schema}", schema))
    _ensured.add(schema)


class Storage:
    def __init__(self, platform_dsn: str, tenant_dsn: str, product: str,
                 schema_of: Callable[[str], str] = org_schema, connect_timeout: int = 10):
        self._platform_dsn, self._tenant_dsn = platform_dsn, tenant_dsn
        self.product, self._schema_of, self._timeout = product, schema_of, connect_timeout

    def _platform(self):
        return psycopg.connect(self._platform_dsn, connect_timeout=self._timeout)

    def _tenant(self, schema: str):
        conn = psycopg.connect(self._tenant_dsn, connect_timeout=self._timeout)
        ensure_storage_tables(conn, schema)
        return conn

    def _used(self, conn, schema: str, kind: str) -> int:
        return vector_bytes(conn, schema) if kind == "vector" else cloud_bytes(conn, schema)

    def may_store(self, tenant_id: str, kind: str, size: int = 0) -> Decision:
        """Ask before writing. Allowed when the plan sets no limit or has room; refused when it would overflow."""
        assert kind in KINDS, kind
        try:
            with self._platform() as platform:
                plan = read_storage_plan(platform, tenant_id)
            if plan is None:
                return Decision(True, "no_subscription")
            limit = plan.vector_bytes if kind == "vector" else plan.cloud_bytes
            if limit is None:
                return Decision(True, "no_limit")
            schema = self._schema_of(tenant_id)
            with self._tenant(schema) as tenant:
                used = self._used(tenant, schema, kind)
                self._tell_at_marks(tenant, schema, tenant_id, kind, used, limit)
            if used + max(0, size) > limit:
                return Decision(False, "full", used, limit)
            return Decision(True, "", used, limit)
        except Exception as exc:  # noqa: BLE001 -- a billing fault must not stop a campaign
            log.warning("storage: could not check %s for %s (%s); letting the write go ahead", kind, tenant_id, exc)
            return Decision(True, "unverified")

    def check(self, tenant_id: str, kind: str, size: int = 0) -> Decision:
        """may_store, raising StorageFull when refused."""
        decision = self.may_store(tenant_id, kind, size)
        if not decision:
            raise StorageFull(kind, decision.used, decision.limit or 0)
        return decision

    def record_object(self, tenant_id: str, kind: str, container: str, path: str, size: int,
                      content_type: Optional[str] = None) -> None:
        """A blob was written: remember it so the organisation's cloud usage is a sum, not a listing."""
        try:
            schema = self._schema_of(tenant_id)
            with self._tenant(schema) as tenant:
                tenant.execute(
                    f'INSERT INTO "{schema}".storage_objects (product, kind, container, path, bytes, content_type) '
                    "VALUES (%s, %s, %s, %s, %s, %s) "
                    "ON CONFLICT (container, path) DO UPDATE SET bytes = EXCLUDED.bytes, content_type = EXCLUDED.content_type, "
                    "  product = EXCLUDED.product, kind = EXCLUDED.kind, created_at = now(), deleted_at = NULL",
                    (self.product, kind, container, path, int(size), content_type))
                tenant.commit()
        except Exception as exc:  # noqa: BLE001
            log.warning("storage: could not record %s/%s for %s (%s)", container, path, tenant_id, exc)

    def forget_object(self, tenant_id: str, container: str, path: str) -> None:
        """A blob was deleted: it stops counting."""
        try:
            schema = self._schema_of(tenant_id)
            with self._tenant(schema) as tenant:
                tenant.execute(f'UPDATE "{schema}".storage_objects SET deleted_at = now() WHERE container = %s AND path = %s '
                               "AND deleted_at IS NULL", (container, path))
                tenant.commit()
        except Exception as exc:  # noqa: BLE001
            log.warning("storage: could not forget %s/%s for %s (%s)", container, path, tenant_id, exc)

    def summary(self, tenant_id: str) -> Optional[dict]:
        """Both meters: used, limit (None = no limit), and what makes them up. None without a subscription."""
        with self._platform() as platform:
            plan = read_storage_plan(platform, tenant_id)
        if plan is None:
            return None
        schema = self._schema_of(tenant_id)
        with self._tenant(schema) as tenant:
            tables = vector_tables(tenant, schema)
            return {
                "vector": {"used": sum(int(s) for _, s in tables), "limit": plan.vector_bytes,
                           "tables": {t: int(s) for t, s in tables}},
                "cloud": {"used": cloud_bytes(tenant, schema), "limit": plan.cloud_bytes,
                          "by_product": cloud_by_product(tenant, schema)},
            }

    def _tell_at_marks(self, tenant, schema: str, tenant_id: str, kind: str, used: int, limit: int) -> None:
        """Owners are told at 80 and 100 percent, once per crossing; a mark clears when usage drops below it."""
        try:
            row = tenant.execute(f'SELECT marks_sent FROM "{schema}".storage_notices WHERE kind = %s', (kind,)).fetchone()
            sent = list(row[0]) if row and row[0] else []
            percent = used * 100 // limit if limit else 0
            now_sent = [m for m in sent if percent >= m]
            crossed = [m for m in MARKS if percent >= m and m not in now_sent]
            now_sent += crossed
            if now_sent != sent:
                # written before anyone is told: a flaky connection may then lose a notice, never double it
                tenant.execute(f'INSERT INTO "{schema}".storage_notices (kind, marks_sent) VALUES (%s, %s::jsonb) '
                               "ON CONFLICT (kind) DO UPDATE SET marks_sent = EXCLUDED.marks_sent, updated_at = now()",
                               (kind, json.dumps(now_sent)))
                tenant.commit()
            what = "vector storage" if kind == "vector" else "storage"
            for mark in crossed:
                if mark >= 100:
                    title, text = (f"GalaxiQ: {what} full",
                                   f"You have used all {limit // MB:,} MB of {what}. Remove what you no longer need, or move to a larger plan.")
                else:
                    title, text = (f"GalaxiQ: {mark}% of your {what} used",
                                   f"You have used {used // MB:,} of {limit // MB:,} MB of {what}.")
                with self._platform() as platform:
                    tell_members(platform, tenant_id, title, text)
        except Exception as exc:  # noqa: BLE001 -- the check stands whether or not it was announced
            log.warning("storage: could not tell the owners of %s about %s (%s)", tenant_id, kind, exc)
