"""DB-backed allowed hosts and CRM webhook resolution (System Admin settings)."""
from __future__ import annotations

import logging
from functools import lru_cache
from urllib.parse import urlparse

logger = logging.getLogger(__name__)

_LOCAL_HOSTS = frozenset({'127.0.0.1', 'localhost'})


def _host_from_url(url: str) -> str:
    url = (url or '').strip()
    if not url:
        return ''
    parsed = urlparse(url if '://' in url else f'https://{url}')
    return (parsed.hostname or '').strip().lower()


def parse_allowed_hosts_csv(text: str) -> set[str]:
    hosts: set[str] = set()
    for part in (text or '').split(','):
        host = part.strip().lower()
        if host:
            hosts.add(host.split(':')[0])
    return hosts


def compute_allowed_hosts(ui_url: str, api_url: str, extra_csv: str) -> str:
    hosts = set(_LOCAL_HOSTS)
    hosts |= parse_allowed_hosts_csv(extra_csv)
    for url in (ui_url, api_url):
        h = _host_from_url(url)
        if h:
            hosts.add(h)
    return ', '.join(sorted(hosts))


@lru_cache(maxsize=1)
def get_allowed_hosts() -> frozenset[str]:
    """Effective Host header allow-list: local dev hosts + DB settings."""
    hosts = set(_LOCAL_HOSTS)
    try:
        from system_administration.models import CompanyIntegrationSettings

        row = CompanyIntegrationSettings.objects.order_by('-last_updated_on').first()
        if row:
            hosts |= parse_allowed_hosts_csv(row.allowed_hosts)
            for url in (row.erp_ui_public_url, row.erp_api_public_url):
                h = _host_from_url(url)
                if h:
                    hosts.add(h)
    except Exception as exc:  # noqa: BLE001
        logger.warning('allowed hosts DB lookup failed: %s', exc)
    return frozenset(hosts)


def clear_allowed_hosts_cache() -> None:
    get_allowed_hosts.cache_clear()


def get_active_crm_integration():
    try:
        from system_administration.models import CompanyIntegrationSettings

        return CompanyIntegrationSettings.objects.filter(crm_webhook_active=True).first()
    except Exception as exc:  # noqa: BLE001
        logger.warning('CRM integration lookup failed: %s', exc)
        return None


def resolve_crm_webhook(field_name: str) -> tuple[str, str]:
    """Return (url, secret) for a CRM outbound webhook field on CompanyIntegrationSettings."""
    row = get_active_crm_integration()
    if not row:
        return '', ''
    url = (getattr(row, field_name, None) or '').strip()
    if not url:
        return '', ''
    return url, row.crm_webhook_secret or ''
