"""
Who this install says it is, in one place.

Public pages, the panel and every email used to carry the company name and
domain as literals. In this template that meant 155 lines reading YOUR COMPANY
and 39 files pointing at example.com, so a client's live site advertised a
placeholder until somebody remembered to edit each file. In the tree it was
copied from, those same lines carried a real company name, which is correct
there and wrong in every copy made from it.

Nothing should know the name. Ask here.
"""
import re


def company_name(tenant=None):
    """Just the name. For an email subject or a line of legal text."""
    return brand(tenant)['company']


def brand(tenant=None):
    """
    Name, absolute site URL and the settings row, for templates.

    Falls back through Settings, then the tenant record, so a half-configured
    install shows its own name rather than a placeholder. Never raises: a
    missing name must not stop an order confirmation going out.
    """
    site = None
    name = ''
    domain = ''
    try:
        from apps.pages.models import SiteSettings
        from apps.tenants.models import Tenant
        if tenant is None or getattr(tenant, 'pk', 0) == 0:
            tenant = Tenant.objects.filter(is_master=True).first()
        site = SiteSettings.load(tenant)
        name = (getattr(site, 'site_name', '') or '').strip()
        if not name and tenant is not None:
            name = (getattr(tenant, 'name', '') or '').strip()
        domain = (getattr(tenant, 'primary_domain', '') or '').strip()
    except Exception:
        pass

    if domain and not domain.startswith(('http://', 'https://')):
        domain = f'https://{domain}'
    if not domain:
        from django.conf import settings as _s
        domain = (getattr(_s, 'SITE_URL', '') or '').rstrip('/')

    url = domain.rstrip('/')
    return {
        'site': site,
        'company': name,
        'site_url': url,
        # The same thing without the scheme, because a footer prints the
        # domain as words rather than as a link target.
        'site_domain': re.sub(r'^https?://', '', url),
    }
