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
    WTF_CSRF_TIME_LIMIT = 3600           # Token valid for 1 hour
    
    # ── 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')
    
    # ── 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)
