"""Explicit integration settings; no production secrets are generated silently."""
import os
from django.conf import settings
from rest_framework.exceptions import ValidationError
from urllib.parse import urlsplit


def value(name, default=''):
    return getattr(settings, name, os.environ.get(name, default))


def origin_for(request):
    allowed = value('ACCOUNT_AUTH_ORIGINS', 'http://127.0.0.1:5173,http://localhost:5173' if settings.DEBUG else '')
    origins = [s.strip().rstrip('/') for s in allowed.split(',') if s.strip()]
    origin = request.headers.get('Origin', '').rstrip('/') or (origins[0] if origins else '')
    parsed = urlsplit(origin)
    if origin not in origins or not parsed.hostname or parsed.path or parsed.query or parsed.fragment:
        raise ValidationError('Authentication origin is not configured or allowed.')
    if parsed.scheme != 'https' and not (settings.DEBUG and parsed.hostname in {'localhost','127.0.0.1'}):
        raise ValidationError('Authentication requires HTTPS.')
    return origin


def rp_for(origin):
    host = urlsplit(origin).hostname
    rp = value('ACCOUNT_PASSKEY_RP_ID') or host
    if host != rp and not host.endswith('.'+rp):
        raise ValidationError('Passkey RP ID does not match this origin.')
    return rp
