"""Resolve the active tenant for an incoming Flask request."""

from __future__ import annotations

from flask import Request
from sqlalchemy.orm import Session

from config.control_plane import get_control_plane_engine
from platform.tenants.models import Tenant


def resolve_tenant(request: Request) -> dict[str, str]:
    """Resolve a tenant from the ``X-Tenant-ID`` header.

    Raises:
        ValueError: when the request does not include a tenant identifier.
        LookupError: when the tenant cannot be found.
        PermissionError: when the tenant exists but is inactive.
    """
    tenant_id = (request.headers.get("X-Tenant-ID") or "").strip()
    if not tenant_id:
        raise ValueError("Missing X-Tenant-ID header")

    engine = get_control_plane_engine()
    with Session(engine, future=True) as session:
        tenant = session.get(Tenant, tenant_id)
        if tenant is None:
            raise LookupError(f"Tenant not found: {tenant_id}")
        if not tenant.is_active or tenant.status != "active":
            raise PermissionError(f"Tenant inactive: {tenant_id}")
        return {
            "tenant_id": tenant.tenant_id,
            "slug": tenant.slug,
            "db_name": tenant.data_db_name or "",
            "storage_key": tenant.storage_key or tenant.slug or tenant.tenant_id,
            "plan": tenant.plan_id or "",
        }


class TenantResolver:
    """Compatibility wrapper around :func:`resolve_tenant`."""

    def resolve_from_request(self, request: Request) -> dict[str, str]:
        return resolve_tenant(request)
