"""Minimal tenant resolver for the SaaS request flow.

This resolver is intentionally lightweight for initial runtime wiring.
It prefers ``X-Tenant-ID`` and falls back to simple host parsing.
"""

from __future__ import annotations

from flask import Request


def resolve_tenant(request: Request) -> dict[str, str]:
    """Resolve the active tenant from headers or host.

    Current bootstrap behavior is intentionally fixed to ``absolutems`` so the
    runtime flow can be tested end-to-end before control-plane lookup is wired.
    """
    tenant_id = (request.headers.get("X-Tenant-ID") or "").strip()
    if not tenant_id:
        host = (request.headers.get("Host") or request.host or "").split(":", 1)[0].strip().lower()
        if host and host != "mail.absolutems.com.au":
            tenant_id = host.split(".", 1)[0]

    if not tenant_id:
        raise ValueError("Missing tenant identifier")

    if tenant_id != "absolutems":
        raise LookupError(f"Unknown tenant: {tenant_id}")

    return {
        "tenant_id": "absolutems",
        "db_name": "absolutems_db",
        "status": "active",
    }

