"""
Django settings for idealogy_api (production).
Reads secrets from ~/.secrets_idealogy.
"""
from pathlib import Path
import mimetypes
mimetypes.add_type('application/manifest+json', '.webmanifest', strict=True)
from datetime import timedelta

import pymysql
pymysql.install_as_MySQLdb()

BASE_DIR = Path(__file__).resolve().parent.parent
SECRETS_FILE = Path.home() / '.secrets_idealogy'

# ---------- Load secrets ----------
_secrets = {}
if SECRETS_FILE.exists():
    with open(SECRETS_FILE, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#') or '=' not in line:
                continue
            key, _, value = line.partition('=')
            _secrets[key.strip()] = value.strip()

SECRET_KEY = _secrets.get('DJANGO_SECRET_KEY', 'unsafe-fallback-change-me')
DEBUG = False

ALLOWED_HOSTS = [h.strip() for h in _secrets.get('ALLOWED_HOSTS', '').split(',') if h.strip()]
if 'testserver' not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append('testserver')

# Fix for Live Nazar AJAX 500 error
if 'www.api-sandbox-idealogy.orkoworo.com' not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append('www.api-sandbox-idealogy.orkoworo.com')
if '.orkoworo.com' not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append('.orkoworo.com')

# ---------- Apps ----------
INSTALLED_APPS = [
    'vault',
    'discipline',
    'integrity',
    'academy',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'engagement',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'django_filters',
    'exams',
    'non_9th',
    'student_engagement',
    'game',
    'workshop',
    'runner',
    'mission_hub',
]

MIDDLEWARE = [
    'exams.middleware_no_cache.NoCacheHTMLMiddleware',
    'exams.middleware_error_capture.ErrorCaptureMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'idealogy_api.middleware.ContentSecurityPolicyMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'integrity.middleware_paste_guard.PasteRateLimitMiddleware',

    'exams.middleware_stale_session.ClearStaleSessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'exams.middleware_preview.PreviewAsMiddleware',
    'engagement.middleware.EngagementTickMiddleware',
    'academy.middleware_portal.GlobalPortalMiddleware',
    # 'integrity.middleware.IntegritySessionMiddleware',  # DISABLED PERMANENTLY (Access Band removed)
    'exams.middleware_parent_ack.ParentAckGateMiddleware',
        'exams.middleware_kernel_guard.KernelGuardMiddleware',
    'exams.middleware.SessionActivityMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    "idealogy_api.middleware_cache.NoCacheForAuthMiddleware",
]

ROOT_URLCONF = 'idealogy_api.urls'

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [BASE_DIR / 'templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
                'exams.context_processors.subjects_context',
                'academy.context_processors.portal_status',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
                'exams.context_processors_banner.kzm_ack_state',
            'django.contrib.messages.context_processors.messages',
                'exams.context_processors.page_guide',
            'exams.context_processors.now_utc',
            'exams.context_processors.incomplete_workflows',
            'exams.context_processors.has_system_work',
        
                    'exams.context_processors.my_books',
                'workshop.context_processors.workshop_pending_count',
                'exams.context_processors_points.points_manager_context',
                'exams.context_processors.upload_key_context',
            ],
    },
}]

WSGI_APPLICATION = 'idealogy_api.wsgi.application'

# ---------- Database ----------
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': _secrets.get('DB_NAME'),
        'USER': _secrets.get('DB_USER'),
        'PASSWORD': _secrets.get('DB_PASSWORD'),
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'charset': 'utf8mb4',
        },
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 10}},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Karachi'
USE_I18N = True
USE_TZ = True

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

# Whitenoise cache settings — keeps cache short for non-hashed files
# so CSS updates take effect immediately after deploy
WHITENOISE_MAX_AGE = 0
WHITENOISE_ALLOW_ALL_ORIGINS = False

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# ---------- DRF ----------
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter'),
    'PAGE_SIZE': 20,
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(hours=8),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}

# ---------- CORS / CSRF ----------
CORS_ALLOWED_ORIGINS = [
    'https://idealogy.orkoworo.com',
]
CORS_ALLOW_CREDENTIALS = True

CSRF_TRUSTED_ORIGINS = [
    'https://idealogy.orkoworo.com',
    'https://api-idealogy.orkoworo.com',
]

# ---------- Security ----------
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 60 * 60 * 24 * 14
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = "Lax"
LOGIN_URL = "/api/portal/login/"
LOGIN_REDIRECT_URL = "/api/portal/"
LOGOUT_REDIRECT_URL = "/api/portal/login/"

FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024

# ---------- Logging ----------
(BASE_DIR / 'tmp').mkdir(exist_ok=True)
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': str(BASE_DIR / 'tmp' / 'django.log'),
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'INFO',
    },
}

# ---------- Idealogy config (Rule 10; Twelve-Factor App Factor III) ----------
# Stable cPanel Terminal path; cPanel appends the per-session token when
# a logged-in user opens it. Do NOT store session tokens here (OWASP
# ASVS 5.0 s7.2.1; ISO 27001 A.8.15).
TERMINAL_URL = "https://orkoworo.com:2083/frontend/jupiter/terminal/"

# Document Vault (outside webroot; OWASP ASVS V12.1)
VAULT_ROOT = "/home/orkoworo/idealogy/vault_files"

LOGGING = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'verbose': {'format': '[%(asctime)s] [%(module)s] %(levelname)s %(message)s'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'stream': __import__('sys').stdout, 'formatter': 'verbose'}}, 'root': {'handlers': ['console'], 'level': 'INFO'}}


# PWA Manifest MIME Type


# ═══════════════════════════════════════════════════════════════
# SECURITY HARDENING — Added 2026-10-17 (SEC-1 / SEC-2)
# ═══════════════════════════════════════════════════════════════

# HTTP Strict Transport Security — instructs browsers to always use HTTPS.
# Started at 1 hour for safe rollout; bump to 31536000 (1 year) after 1 week
# of successful production run.
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = False   # Set to True only after HSTS_SECONDS >= 31536000

# Defense-in-depth: Django duplicate headers that LiteSpeed already adds.
# Harmless duplicate, safer if server config ever changes.
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'

# Referrer policy — prevents leaking full URLs to third parties
SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'

# Allow session cookies to be set only over HTTPS (already True, confirmed)
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = False  # Must be False for Django CSRF tokens in forms


# Unicode Safety (fixes emoji encoding crashes)
DEFAULT_CHARSET = 'utf-8'
FILE_CHARSET = 'utf-8'


# Fix for 400 Bad Request on large class-homework forms
DATA_UPLOAD_MAX_NUMBER_FIELDS = 5000


HANDLER403_TRACE = True
def custom_403_handler(request, exception):
    import traceback
    print('=== 403 TRACEBACK ===')
    traceback.print_exc()
    from django.views.defaults import permission_denied
    return permission_denied(request, exception)
handler403 = 'idealogy_api.settings.custom_403_handler'


# --- AUTHENTICATION & EMAIL (Phase 2) ---
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'noreply@idealogy.orkoworo.com'
