from django.conf import settings as django_settings
from .models import SiteSettings, SocialLink, PartnerLogo, LegalPage, FooterLink


def _resolve_tenant(request):
    """Return a real DB tenant (never the dev placeholder with pk=0).

    Kept as a thin wrapper so existing callers do not change. The rule lives
    in apps/tenants/resolve.py, in one place, because three copies of it is
    how an unrecognised Host ended up rendering another site's branding.
    """
    from apps.tenants.resolve import resolve_tenant
    return resolve_tenant(request)



def _nav_pages(tenant):
    """The public menu, built from what the site actually has.

    A blank install should not advertise a Services page with no services on
    it. Each entry appears only once there is something behind it, so the menu
    grows as the site is filled in rather than starting full of dead links.
    """
    pages = []
    checks = (
        ('/services/',  'Services',  'apps.pages.models',      'Service',       {'is_active': True}),
        ('/portfolio/', 'Portfolio', 'apps.portfolio.models',  'PortfolioItem', {'is_active': True}),
        ('/insights/',  'Insights',  'apps.insights.models',   'Insight',       {'status': 'published'}),
        ('/faq/',       'FAQ',       'apps.faq.models',        'FAQItem',       {'is_active': True}),
    )
    for url, label, module, model_name, flt in checks:
        try:
            model = getattr(__import__(module, fromlist=[model_name]), model_name)
            if model.objects.filter(**flt).exists():
                pages.append({'url': url, 'label': label})
        except Exception:
            continue
    return pages

def global_settings(request):
    """
    Inject per-tenant SiteSettings + active social links into every template.
    Falls back gracefully if tables don't exist yet.
    """
    tenant = _resolve_tenant(request)
    site = SiteSettings.load(tenant)

    try:
        social_links = list(
            SocialLink.objects.filter(tenant=tenant, is_active=True).order_by('order', 'platform')
        )
    except Exception:
        social_links = []

    try:
        _logos = PartnerLogo.objects.filter(is_active=True).order_by('order')
        global_partners = list(_logos.filter(logo_type='partner'))
        global_clients  = list(_logos.filter(logo_type='client'))
    except Exception:
        global_partners = []
        global_clients  = []

    try:
        legal_pages = list(
            LegalPage.objects.filter(tenant=tenant, is_visible=True).order_by('order', 'slug')
        )
    except Exception:
        legal_pages = []

    try:
        _flinks = FooterLink.objects.filter(tenant=tenant, is_active=True).order_by('column', 'order')
        footer_links_by_column = {}
        for fl in _flinks:
            footer_links_by_column.setdefault(fl.column, []).append(fl)
    except Exception:
        footer_links_by_column = {}

    # company and site_url come from the same helper the emails use, so a
    # page and the email it triggers can never disagree about who sent it.
    from .branding import brand
    _b = brand(tenant)

    return {
        'site': site,
        'company': _b['company'],
        'site_url': _b['site_url'],
        'site_domain': _b['site_domain'],
        'social_links': social_links,
        'global_partners': global_partners,
        'global_clients': global_clients,
        'legal_pages': legal_pages,
        'nav_pages': _nav_pages(tenant),
        'footer_links_by_column': footer_links_by_column,
        'cms_version': getattr(django_settings, 'CMS_VERSION', ''),
        # True only on the install that runs the fleet. Tenant.is_master is
        # not this: every install has one master row carrying its own
        # identity, so gating on it showed Tenants and Fleet to every client.
        # An install that reports to somebody has an upstream and is not it.
        'is_fleet_master': not (getattr(django_settings, 'FT_CONTROL_URL', '') or ''),
        # Who built the panel, for the line at the foot of the sidebar. A
        # tenant install knows this without being told: it is whoever it
        # reports to. Derived from the check-in URL rather than written into
        # the template, which has to stay free of any one company's name.
        # On the fleet master there is no upstream, so it names itself.
        'panel_credit': _panel_credit(request, tenant),
    }


def _panel_credit(request, tenant):
    """The domain to credit at the foot of the panel sidebar.

    A client's panel is built and run by whoever operates the fleet, and the
    sidebar said the client's own domain, which reads as though they built it
    themselves. The fleet master's address is already in FT_CONTROL_URL, so
    the name comes from configuration rather than from a literal in a template
    that ships to every client server.

    panel.example.com becomes example.com, since the panel subdomain is an
    implementation detail and not the brand.
    """
    from django.conf import settings as _s
    url = (getattr(_s, 'FT_CONTROL_URL', '') or '').strip()
    if url and '://' in url:
        host = url.split('://', 1)[1].split('/', 1)[0].split(':')[0]
        for prefix in ('panel.', 'www.'):
            if host.startswith(prefix):
                host = host[len(prefix):]
        if host:
            return host
    # No upstream: this install is the master and credits itself.
    return (getattr(tenant, 'primary_domain', '') or getattr(tenant, 'name', '') or '')
