import os
from datetime import timedelta
from pathlib import Path


def _resolve_path(env_var, default_subpath):
    """Resolve a path from environment variable.

    - Absolute paths (/app/data/...) are used as-is
    - Relative paths (./data/...) are resolved relative to CWD
    - No env var: use default relative to CWD
    """
    env_val = os.environ.get(env_var, '').strip()
    if not env_val:
        return str(Path.cwd() / default_subpath)
    if os.path.isabs(env_val):
        return env_val
    return str(Path.cwd() / env_val)


class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-me')

    # Database
    SQLALCHEMY_DATABASE_URI = f'sqlite:///{_resolve_path("DATABASE_PATH", "data/minicloud.db")}'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # File uploads
    UPLOAD_PATH = _resolve_path('UPLOAD_PATH', 'data/files')
    MAX_CONTENT_LENGTH = int(os.environ.get('MAX_UPLOAD_SIZE_MB', 500)) * 1024 * 1024

    # JWT
    JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY', 'dev-jwt-secret-change-me')
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(
        seconds=int(os.environ.get('JWT_ACCESS_TOKEN_EXPIRES', 900))
    )
    JWT_REFRESH_TOKEN_EXPIRES = timedelta(
        seconds=int(os.environ.get('JWT_REFRESH_TOKEN_EXPIRES', 604800))
    )

    # CORS
    FRONTEND_URL = os.environ.get('FRONTEND_URL', 'http://localhost:3000')
