import os
from pathlib import Path

# Windows-safe: keep forward slashes so the sqlite URI always parses
BASE_DIR = Path(__file__).resolve().parent.parent


def _default_sqlite_uri():
    """Build a portable sqlite URI that works on Windows, Linux and macOS."""
    db_path = (BASE_DIR / "data.sqlite").as_posix()
    return "sqlite:///" + db_path


def _resolve_database_uri():
    """
    Prefer DATABASE_URL from the host environment, but never crash the app:
    - fixes postgres:// -> postgresql:// (common on free hosts)
    - falls back to the local sqlite file if the URL is unparsable
      (this was the cause of 'Could not parse SQLAlchemy URL' startup crash)
    """
    url = (os.environ.get("DATABASE_URL") or "").strip()
    if url:
        if url.startswith("postgres://"):
            url = url.replace("postgres://", "postgresql://", 1)
        try:
            from sqlalchemy.engine import make_url
            make_url(url)
            return url
        except Exception:
            pass
    return _default_sqlite_uri()


class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY", "change-me-in-production-arena")
    SQLALCHEMY_DATABASE_URI = _resolve_database_uri()
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    UPLOAD_FOLDER = os.path.join(BASE_DIR, "app", "static", "uploads")
    MAX_CONTENT_LENGTH = 8 * 1024 * 1024
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"
    DEFAULT_LANG = "en"
    DEFAULT_REGION = "global"
    INTRO_VIDEO_URL = os.environ.get("INTRO_VIDEO_URL", "")
    OTP_TTL_MINUTES = 15
    ASSET_VERSION = "v4"  # bump to bust static cache on updates


class DevelopmentConfig(Config):
    DEBUG = True


class ProductionConfig(Config):
    DEBUG = False
    # Only force Secure cookies when the deployment actually uses HTTPS.
    # On plain-HTTP cheap hosts, Secure cookies are dropped by the browser
    # and login silently stops working — so default is False; set
    # FORCE_HTTPS=1 on the host when a TLS certificate is available.
    SESSION_COOKIE_SECURE = os.environ.get("FORCE_HTTPS", "0") == "1"


config_by_name = {
    "development": DevelopmentConfig,
    "production": ProductionConfig,
}
