"""Each organisation's files in its own Azure container, the same way in every product.

The container is the one the platform mapped to the tenant (master `Tenants.bucketName`, normalised as Node's
normalizeAzureContainerName does): never derived from an id, never taken from a request, never a shared fallback.
Files sit at the container's root by category (hero/, brand/, chat/<thread>/, ...). Containers are private; a file a
customer's mail client or browser must load is served by Node through a permanent signed link
(`sign_asset_url`), so no Azure address or credential leaves a product for a new file.

Products pass their own connection, Azure client, base URL and signing key; nothing here reads settings.
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import re
from typing import Iterable, Optional, Tuple

UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
# Every product writes into the tenant's container under one of five folders: media/, my-templates/, knowledge-base/,
# chat/, renders/. The images and videos of these four may be shown to anyone holding the link; a knowledge-base
# document never is. Node serves exactly these: a new one is added on both sides.
SHARED_CATEGORIES = ("media", "my-templates", "chat", "renders")
SHARED_EXTENSIONS = ("png", "jpg", "jpeg", "webp", "gif", "mp4")
LINK_PATH = "/api/public/tenant-assets/"
# Node serves a tenant's own templates on a route of their own, signed the same way.
TEMPLATE_LINK_PATH = "/api/public/template-assets/"


def tenant_uuid(tenant_id: str) -> str:
    """The tenant's id as the master table holds it; a schema name (org_<id>) names the same tenant."""
    tid = str(tenant_id or "").strip().lower()
    tid = tid[4:] if tid.startswith("org_") else tid
    if not UUID.match(tid):
        raise ValueError(f"{tenant_id!r} is not a tenant id")
    return tid


def container_name(raw: str) -> str:
    """Node's normalizeAzureContainerName without its fallback: lowercase, underscores and anything not a letter,
    digit or hyphen become hyphens, runs collapse, ends trimmed, 3 to 63 characters."""
    s = re.sub(r"[^a-z0-9-]", "-", str(raw or "").strip().lower().replace("_", "-"))
    s = re.sub(r"-+", "-", s).strip("-")
    if not 3 <= len(s) <= 63:
        raise ValueError(f"{raw!r} is not a usable Azure container name")
    return s


def read_tenant_container(conn, tenant_id: str) -> str:
    """The container mapped to this tenant, read with a connection to the master database: an Azure tenant that is
    not deleted and has a mapping. Anything else is refused."""
    tid = tenant_uuid(tenant_id)
    row = conn.execute('SELECT "bucketName", "storageProvider" FROM public."Tenants" '
                       'WHERE id = %s AND NOT coalesce("isDeleted", false)', (tid,)).fetchone()
    if not row:
        raise ValueError(f"tenant {tid} is not an active tenant")
    bucket, provider = (row["bucketName"], row["storageProvider"]) if isinstance(row, dict) else row
    if str(provider or "").lower() != "azure":
        raise ValueError(f"tenant {tid} does not store on Azure")
    if not bucket:
        raise ValueError(f"tenant {tid} has no storage container mapped")
    return container_name(bucket)


def require_access(service, container: str):
    """The container's client, created privately when missing (another request creating it first is fine). An
    existing container's access is never changed here."""
    from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError
    client = service.get_container_client(container)
    try:
        client.get_container_properties()
    except ResourceNotFoundError:
        try:
            service.create_container(container)
        except ResourceExistsError:
            pass
    return client


def stored_location(container: str, key: str, tenant_id: str) -> str:
    """How a product records a file: its container, its key and its tenant, in one string."""
    return f"azure://{container}/{key}#tenant={tenant_uuid(tenant_id)}"


def attachment_location(stored: str, legacy_container: str) -> Tuple[str, str]:
    """(container, key) of a recorded file: a container-qualified location, or a legacy path in the shared one."""
    stored = str(stored or "")
    if stored.startswith("azure://"):
        container, _, key = stored[len("azure://"):].split("#", 1)[0].partition("/")
        return container, key
    return legacy_container, stored


def attachment_tenant(stored: str) -> Optional[str]:
    """The tenant a recorded file belongs to: written into a new location, or the first folder of a legacy path."""
    stored = str(stored or "")
    if stored.startswith("azure://"):
        found = re.search(r"#tenant=([0-9a-f-]{36})$", stored)
        return found.group(1) if found else None
    try:
        return tenant_uuid(stored.split("/", 1)[0])
    except ValueError:
        return None


def check_shareable(key: str, categories: Iterable[str] = SHARED_CATEGORIES) -> None:
    """Only images and videos of the shared categories, by a plain path: never a chat original, a document, or a
    path that climbs out of its folder."""
    parts = str(key or "").split("/")
    if (not key or key.startswith("/") or "\\" in key or any(p in ("", ".", "..") for p in parts)
            or parts[0] not in tuple(categories)):
        raise ValueError(f"{key!r} is not a file that may be shared")
    if key.rsplit(".", 1)[-1].lower() not in SHARED_EXTENSIONS:
        raise ValueError(f"{key!r} is not an image or a video")


def _b64(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")


def sign_asset_url(base_url: str, secret: str, tenant_id: str, key: str,
                   categories: Iterable[str] = SHARED_CATEGORIES) -> str:
    """The permanent link Node serves this file at: base64url JSON {tenantId, key}, a dot, base64url HMAC-SHA256 of
    that text with the shared key. Anyone holding it can view the file; nothing about Azure is in it."""
    check_shareable(key, categories)
    base = str(base_url or "").rstrip("/")
    if not base or base.endswith("/api"):
        raise ValueError("the tenant asset base URL is not set, or ends in /api")
    if len(str(secret or "").encode()) < 32:
        raise ValueError("the tenant asset signing key is not set or shorter than 32 bytes")
    payload = _b64(json.dumps({"tenantId": tenant_uuid(tenant_id), "key": key}, separators=(",", ":")).encode())
    signature = _b64(hmac.new(secret.encode(), payload.encode(), hashlib.sha256).digest())
    path = TEMPLATE_LINK_PATH if key.startswith("my-templates/") else LINK_PATH
    return f"{base}{path}{payload}.{signature}"


def key_of_asset_url(url: str) -> Optional[str]:
    """The file a signed link points at, read back from its payload; None for any other address."""
    found = re.search(f"(?:{re.escape(LINK_PATH)}|{re.escape(TEMPLATE_LINK_PATH)})" + r"([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+",
                      str(url or ""))
    if not found:
        return None
    payload = found.group(1)
    try:
        return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))).get("key")
    except ValueError:
        return None
