"""FTG2 beta configuration audit. Pure stdlib; no DB connections or writes.

Usage: python deploy/beta/release_audit.py
Reads deploy/beta/.env.server and never prints values of secrets.
"""
from pathlib import Path
from urllib.parse import urlsplit
import sys

ROOT = Path(__file__).resolve().parent
REQUIRED = (
    'FTG_DOMAIN', 'DJANGO_ALLOWED_HOSTS', 'DJANGO_SECRET_KEY',
    'POSTGRES_DB', 'POSTGRES_USER', 'POSTGRES_PASSWORD', 'ACCOUNT_FRONTEND_URL',
    'DEFAULT_FROM_EMAIL', 'EMAIL_HOST', 'EMAIL_HOST_USER', 'EMAIL_HOST_PASSWORD',
    'FTG_BETA_REGISTRATION_CODE',
)


def parse_file(file: Path) -> dict[str, str]:
    if not file.is_file():
        raise ValueError('Missing deploy/beta/.env.server (copy .env.server.example on SERVER only).')
    result = {}
    for raw in file.read_text(encoding='utf-8-sig').splitlines():
        raw = raw.strip()
        if not raw or raw.startswith('#') or '=' not in raw:
            continue
        k, v = raw.split('=', 1)
        result[k.strip()] = v.strip().strip('"\'')
    return result


def audit(values: dict[str, str]) -> list[str]:
    issues = []
    for key in REQUIRED:
        val = values.get(key, '')
        if not val or 'REPLACE' in val or '.example.com' in val:
            issues.append(f'{key}: missing / placeholder')
    if values.get('DJANGO_DEBUG', '').lower() != 'false':
        issues.append('DJANGO_DEBUG must be false')
    if len(values.get('DJANGO_SECRET_KEY', '')) < 50:
        issues.append('DJANGO_SECRET_KEY must be >= 50 characters')
    if len(values.get('FTG_BETA_REGISTRATION_CODE', '')) < 24:
        issues.append('FTG_BETA_REGISTRATION_CODE must be >= 24 characters')
    if values.get('POSTGRES_DB') in {'football_game', 'ftg2_test_20261017', 'postgres'}:
        issues.append('POSTGRES_DB must be an isolated new FTG2 beta database')
    host = values.get('FTG_DOMAIN', '')
    if not host or host in {'localhost', '127.0.0.1'} or '*' in host or '/' in host:
        issues.append('FTG_DOMAIN must be a real public hostname')
    hosts = [v.strip() for v in values.get('DJANGO_ALLOWED_HOSTS', '').split(',')]
    if '*' in hosts or host not in hosts:
        issues.append('DJANGO_ALLOWED_HOSTS must contain FTG_DOMAIN (not wildcard)')
    frontend = urlsplit(values.get('ACCOUNT_FRONTEND_URL', ''))
    if frontend.scheme != 'https' or frontend.hostname != host:
        issues.append('ACCOUNT_FRONTEND_URL must use the matching HTTPS hostname')
    if values.get('EMAIL_BACKEND') != 'django.core.mail.backends.smtp.EmailBackend':
        issues.append('EMAIL_BACKEND must be SMTP')
    return issues


def main() -> int:
    try:
        errors = audit(parse_file(ROOT / '.env.server'))
    except (ValueError, OSError) as e:
        print(f'NO-GO: {e}')
        return 1
    if errors:
        print('NO-GO: beta release configuration has unresolved issues:')
        for e in errors:
            print(f'  - {e}')
        return 1
    print('CONFIG AUDIT OK (offline). Still run Django checks, Postgres/Redis preflight and E2E tests.')
    return 0


if __name__ == '__main__':
    sys.exit(main())
