"""
Utility functions for tenant operations.
"""
from .models import Tenant, TenantModule, DEFAULT_MODULES, ALWAYS_ON_MODULES, MODULE_CHOICES


def provision_tenant(name, primary_domain, cms_subdomain, owner=None,
                     plan='business', modules=None, accent_colour='#e8b400'):
    """
    Create a new tenant with its default module set.
    Call this when onboarding a new client site.
    """
    tenant = Tenant.objects.create(
        name=name,
        primary_domain=primary_domain,
        cms_subdomain=cms_subdomain,
        owner=owner,
        plan=plan,
        accent_colour=accent_colour,
    )

    # Enable requested modules (default set if not specified)
    module_set = modules if modules is not None else DEFAULT_MODULES
    module_set = module_set | ALWAYS_ON_MODULES  # always-on are always added

    all_module_keys = {k for k, _ in MODULE_CHOICES}
    for module_key in all_module_keys:
        TenantModule.objects.create(
            tenant=tenant,
            module=module_key,
            is_enabled=(module_key in module_set),
        )

    return tenant


def get_tenant_from_host(host):
    """
    Resolve a Tenant from an HTTP Host header.
    Strips port if present. Checks primary_domain, cms_subdomain, extra_domains.
    Returns Tenant or None.
    """
    if not host:
        return None

    # Strip port
    host = host.split(':')[0].lower().strip()

    # Direct match on primary or CMS subdomain
    try:
        return Tenant.objects.get(primary_domain=host, is_active=True)
    except Tenant.DoesNotExist:
        pass

    try:
        return Tenant.objects.get(cms_subdomain=host, is_active=True)
    except Tenant.DoesNotExist:
        pass

    # Check extra_domains (line by line)
    for tenant in Tenant.objects.filter(is_active=True).exclude(extra_domains=''):
        for domain in tenant.extra_domains.splitlines():
            if domain.strip().lower() == host:
                return tenant

    return None
