import os
from contextvars import ContextVar
from typing import Optional

from .models import Client

_current_client_id: ContextVar[Optional[int]] = ContextVar("current_client_id", default=None)


def get_default_client_slug() -> str:
    return os.getenv("DEFAULT_CLIENT_SLUG", "default")


def get_default_client() -> Optional[Client]:
    slug = get_default_client_slug()
    return Client.objects.filter(slug=slug, is_active=True).first()


def set_current_client(client: Optional[Client]) -> None:
    _current_client_id.set(client.id if client else None)


def clear_current_client() -> None:
    _current_client_id.set(None)


def _normalize_host(host: str) -> str:
    return (host or "").split(":")[0].strip().lower()


def _extract_subdomain(host: str) -> Optional[str]:
    host = _normalize_host(host)
    if not host or host in ("localhost", "127.0.0.1"):
        return None
    if host.endswith(".localhost"):
        return host.split(".")[0]
    parts = host.split(".")
    # Basic SaaS host pattern: {subdomain}.{domain}.{tld}
    if len(parts) >= 3 and parts[0] not in ("www", "api"):
        return parts[0]
    return None


def resolve_client_from_host(host: str) -> Optional[Client]:
    subdomain = _extract_subdomain(host)
    if not subdomain:
        return None
    return Client.objects.filter(subdomain=subdomain, is_active=True).first()


def resolve_forced_workspace_client() -> Optional[Client]:
    """
    Optional single-tenant override (e.g. FORCE_WORKSPACE_SUBDOMAIN=nixon) when
    host/header do not resolve a client — same era as apex-only dashboard.
    """
    forced = (os.getenv("FORCE_WORKSPACE_SUBDOMAIN") or "").strip().lower()
    if not forced or not all(c.isalnum() or c == "-" for c in forced):
        return None
    return Client.objects.filter(subdomain=forced, is_active=True).first()


def get_resolved_workspace_client() -> Optional[Client]:
    """
    Tenant for this request from host / X-Workspace-Subdomain only (middleware).
    No DEFAULT_CLIENT_SLUG fallback — use for public branding on apex hosts.
    """
    client_id = _current_client_id.get()
    if not client_id:
        return None
    return Client.objects.filter(id=client_id, is_active=True).first()


def get_current_client() -> Optional[Client]:
    client_id = _current_client_id.get()
    if client_id:
        client = Client.objects.filter(id=client_id, is_active=True).first()
        if client:
            return client
    return get_default_client()
