"""Fail-closed beta production settings.

Use only with DJANGO_SETTINGS_MODULE=config.release_settings on a dedicated
PostgreSQL database. The local Windows/PyCharm settings stay unchanged.
"""
import os
from urllib.parse import urlsplit
from django.core.exceptions import ImproperlyConfigured
from .settings import *  # noqa: F401,F403


def _required(name: str) -> str:
    val = os.environ.get(name, '').strip()
    if not val:
        raise ImproperlyConfigured(f'FTG production setting {name} is required.')
    return val


if os.environ.get('DJANGO_DEBUG', '').lower() not in {'false', '0'} or DEBUG:
    raise ImproperlyConfigured('Set DJANGO_DEBUG=false for the release profile.')
if os.environ.get('FTG_DISABLE_DOTENV', '') != '1':
    raise ImproperlyConfigured('Set FTG_DISABLE_DOTENV=1; never load a local .env in production.')
secret = _required('DJANGO_SECRET_KEY')
if len(secret) < 50 or secret.startswith('django-insecure-') or 'replace' in secret.lower():
    raise ImproperlyConfigured('Use an independent, high-entropy DJANGO_SECRET_KEY (>= 50 characters).')
allowed = [v.strip() for v in _required('DJANGO_ALLOWED_HOSTS').split(',') if v.strip()]
if not allowed or '*' in allowed or any(v in {'localhost', '127.0.0.1', '[::1]'} or v.endswith('.example.com') for v in allowed):
    raise ImproperlyConfigured('Use explicit public hosts only (no wildcard/localhost).')
ALLOWED_HOSTS = allowed
if DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql':
    raise ImproperlyConfigured('Release requires PostgreSQL; SQLite is forbidden.')
if DATABASES['default']['NAME'] in {'football_game', 'ftg2_test_20261017', '', 'postgres'} or not str(DATABASES['default']['NAME']).startswith('ftg2_beta_'):
    raise ImproperlyConfigured('Use a separate new FTG beta database; never connect to existing/local databases.')
if DATABASES['default']['NAME'] != _required('POSTGRES_DB'):
    raise ImproperlyConfigured('Database configuration mismatch; refusing to connect.')
if 'replace' in _required('POSTGRES_PASSWORD').lower():
    raise ImproperlyConfigured('POSTGRES_PASSWORD must not be a placeholder.')
redis = _required('REDIS_URL')
if not redis.startswith(('redis://', 'rediss://')):
    raise ImproperlyConfigured('REDIS_URL must point to Redis.')
if 'redis' not in CACHES['default']['BACKEND'].lower():
    raise ImproperlyConfigured('Release requires shared Redis cache for throttling and locks.')
front = _required('ACCOUNT_FRONTEND_URL')
parsed = urlsplit(front)
if parsed.scheme != 'https' or not parsed.hostname or parsed.hostname in {'localhost', '127.0.0.1'}:
    raise ImproperlyConfigured('ACCOUNT_FRONTEND_URL must be a public HTTPS address.')
if parsed.hostname not in ALLOWED_HOSTS:
    raise ImproperlyConfigured('Frontend hostname must appear in DJANGO_ALLOWED_HOSTS.')
if not DEFAULT_FROM_EMAIL or '@localhost' in DEFAULT_FROM_EMAIL or '@example.com' in DEFAULT_FROM_EMAIL:
    raise ImproperlyConfigured('Set DEFAULT_FROM_EMAIL to a verified sending domain.')
if MAILERS['default']['BACKEND'] != 'django.core.mail.backends.smtp.EmailBackend':
    raise ImproperlyConfigured('Configure real SMTP delivery in the release environment.')
if _required('EMAIL_HOST').endswith('.example.com'):
    raise ImproperlyConfigured('EMAIL_HOST must not be an example placeholder.')
_required('EMAIL_HOST_USER')
if 'replace' in _required('EMAIL_HOST_PASSWORD').lower():
    raise ImproperlyConfigured('EMAIL_HOST_PASSWORD must not be a placeholder.')

DEBUG = False
FTG_RELEASE_PROFILE = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'
# Begin beta with a short HSTS; increase only after HTTPS is stable.
SECURE_HSTS_SECONDS = int(os.environ.get('SECURE_HSTS_SECONDS', '300'))
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
USE_X_FORWARDED_HOST = False
CSRF_TRUSTED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS]
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS]
# Regulator evidence is private. Do not expose MEDIA_ROOT as a public static path.
REGULATORY_EVIDENCE_REQUIRE_MALWARE_SCAN = True
# Ensure private runtime surfaces are not world readable.
FILE_UPLOAD_PERMISSIONS = 0o640
FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o750
RUNTIME_REQUIRE_WORKER_HEARTBEAT = True

# Closed beta: keep registration inaccessible without an invitation.
invite_code = _required('FTG_BETA_REGISTRATION_CODE')
if len(invite_code) < 24 or 'replace' in invite_code.lower():
    raise ImproperlyConfigured('FTG_BETA_REGISTRATION_CODE must be independently random and at least 24 characters.')
FTG_BETA_REGISTRATION_CODE = invite_code
MIDDLEWARE = ['core_runtime.beta_access.BetaSignupGateMiddleware', *MIDDLEWARE]
