import os
import secrets
import warnings
from dotenv import load_dotenv
from datetime import timedelta

load_dotenv()

class Config:
    """Application configuration"""
    
    # ── Secret Key ──────────────────────────────────────────────────────────
    # CRITICAL: Must be set in .env for production!
    # If missing, a random key is generated (sessions reset on restart).
    SECRET_KEY = os.getenv('SECRET_KEY', '')
    if not SECRET_KEY:
        SECRET_KEY = secrets.token_hex(32)
        warnings.warn(
            "⚠️  SECRET_KEY not set! Using auto-generated key. "
            "Sessions will reset on restart. Set SECRET_KEY in .env for production.",
            RuntimeWarning,
            stacklevel=2
        )
    
    # ── Database ────────────────────────────────────────────────────────────
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', 'sqlite:///aliothpress.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
    
    # ── Session Security ────────────────────────────────────────────────────
    PERMANENT_SESSION_LIFETIME = timedelta(hours=12)
    SESSION_COOKIE_HTTPONLY = True        # JS cannot access session cookie
    SESSION_COOKIE_SAMESITE = 'Lax'      # CSRF mitigation
    # SESSION_COOKIE_SECURE = True        # Uncomment when using HTTPS
    
    # ── CSRF Protection ─────────────────────────────────────────────────────
    WTF_CSRF_ENABLED = True
    # None = token lives as long as the session (PERMANENT_SESSION_LIFETIME = 12h)
    # instead of an arbitrary 1h that was SHORTER than the session — which let an
    # editor stay logged in while the token quietly died, surfacing as "save
    # failed" on long edits. Put a number of seconds here (e.g. 28800 = 8h) if you
    # prefer a bounded token lifetime.
    WTF_CSRF_TIME_LIMIT = None
    
    # ── Menus ────────────────────────────────────────────────────────────────
    # Maximum menu nesting depth in TIERS: 3 = top level + children + grand-
    # children. Enforced in both the resolver and the save endpoint (deeper
    # client input is clamped server-side). A future module (e.g. shop with
    # deep category trees) can raise this without touching menu logic.
    MENU_MAX_DEPTH = 3

    # ── Upload folders ──────────────────────────────────────────────────────
    UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads')
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB max file size
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'}
    
    # ── Image processing — automatic optimization on upload ─────────────────
    IMAGE_MAX_DIMENSION = 2560         # Max width/height in px (larger images are resized down)
    IMAGE_VARIANT_WIDTHS = [400, 800, 1200, 1920]  # Responsive breakpoints for srcset
    IMAGE_QUALITY_WEBP = 82            # WebP quality (80-85 is optimal balance)
    IMAGE_QUALITY_AVIF = 68            # AVIF quality (lower number = smaller file, 60-72 is good)
    IMAGE_QUALITY_ORIGINAL = 85        # Quality for resized original format (JPEG)
    
    # ── AI Services ─────────────────────────────────────────────────────────
    ANTHROPIC_API_KEY = os.getenv('ANTHROPIC_API_KEY', '')
    
    # ── License & Updates ───────────────────────────────────────────────────
    UPDATE_SERVER_URL = os.getenv('UPDATE_SERVER_URL', 'https://updates.aliothpress.com')
    
    # ── Demo Mode ───────────────────────────────────────────────────────────
    # Read-only public demo installation (e.g. demo.example.com). When true:
    #   • ALL saving / publishing / uploading / sending is blocked app-wide
    #     (global write barrier in app.py → demo_mode_guard)
    #   • password recovery and invitation pages are disabled entirely
    #   • the guest account below is auto-(re)created on startup and its
    #     credentials are prefilled on the login page
    # To administer a demo site: set DEMO_MODE=false, restart, make changes,
    # re-enable. There is deliberately no in-band bypass.
    DEMO_MODE = os.getenv('DEMO_MODE', 'false').strip().lower() in ('true', '1', 'yes', 'on')
    DEMO_USERNAME = os.getenv('DEMO_USERNAME', 'demo')
    DEMO_PASSWORD = os.getenv('DEMO_PASSWORD', 'demo')
    DEMO_EMAIL = os.getenv('DEMO_EMAIL', 'demo@example.com')
    
    # ── Pagination ──────────────────────────────────────────────────────────
    POSTS_PER_PAGE = 10
    
    # ── Default language ────────────────────────────────────────────────────
    # Available languages are defined in models.py (AVAILABLE_LANGUAGES).
    # Active languages per site are managed via Settings → Languages in admin.
    DEFAULT_LANGUAGE = 'en'
    
    # ── SEO defaults ────────────────────────────────────────────────────────
    DEFAULT_OG_IMAGE = '/static/images/default-og-image.jpg'
    SITE_NAME = 'AliothPress'
    SITE_TAGLINE = 'Create once, publish everywhere'
    
    # ── Password Policy ─────────────────────────────────────────────────────
    PASSWORD_MIN_LENGTH = 8
    PASSWORD_REQUIRE_UPPERCASE = True
    PASSWORD_REQUIRE_LOWERCASE = True
    PASSWORD_REQUIRE_DIGIT = True
    
    @staticmethod
    def init_app(app):
        """Initialize application"""
        # Create upload folder if it doesn't exist
        os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
