"""
One place that answers "which tenant is this request for".

There were three copies of this logic, in the pages context processor, in
cms_views and in the contact views, and all three ended the same way: if the
Host did not match a tenant, fall back to the row with is_master=True. On an
install that holds one tenant that is harmless, because the master row is the
site. On Final Target, which holds a row for every client in the fleet, it
means an unrecognised Host renders as whatever the master row says, so a
misconfigured domain quietly serves someone else's branding instead of
failing where anyone would notice.

A completely unknown Host is already rejected by ALLOWED_HOSTS. What reaches
here is a host that is allowed but not on any tenant row: a bare IP,
localhost, a health check, a www variant nobody added. So the fallback stays,
but it is now narrow and it is noisy.
"""

import logging

log = logging.getLogger(__name__)

_warned = set()


def resolve_tenant(request):
    """The tenant for this request, or None.

    Falls back to the master row only when this install holds exactly one
    tenant, which is the case for every client site. An install with several
    tenant rows gets None rather than a guess.
    """
    tenant = getattr(request, 'tenant', None)
    if tenant is not None and getattr(tenant, 'pk', 0) != 0:
        return tenant

    from apps.tenants.models import Tenant

    try:
        rows = list(Tenant.objects.all()[:2])
    except Exception:
        return None

    host = ''
    try:
        host = (request.get_host() or '').split(':')[0].lower()
    except Exception:
        pass

    if len(rows) == 1:
        only = rows[0]
        if host and host not in _warned:
            _warned.add(host)
            log.warning(
                'Host %r is not on the tenant row for %r. Add it to '
                'primary_domain, cms_subdomain or extra_domains, otherwise '
                'the site is being served by a fallback rather than by name.',
                host, getattr(only, 'name', '?'),
            )
        return only

    # More than one tenant lives here, so there is no safe guess. Returning
    # the master would serve one client's settings under another's domain.
    if host and host not in _warned:
        _warned.add(host)
        log.error(
            'Host %r matched no tenant on an install holding %d tenants. '
            'Refusing to guess.', host, len(rows),
        )
    return None
