"""Environment-driven configuration."""
import os
import re
from datetime import timedelta


def _bool(value, default=False):
    if value is None:
        return default
    return str(value).strip().lower() in ("1", "true", "yes", "on")


def _emails(value):
    """Parse one or more emails separated by comma, semicolon or whitespace."""
    if not value:
        return []
    parts = re.split(r"[,;\s]+", value.strip())
    return [p.strip().lower() for p in parts if p.strip()]


class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY", "dev-insecure-change-me")

    # Google OAuth (from Google Cloud Console). Placeholders until you fill .env.
    GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "")
    GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", "")

    # The whitelisted lead / admin Gmail address(es). One or more, separated by
    # comma, semicolon or space (e.g. "a@gmail.com, b@gmail.com").
    ADMIN_EMAILS = _emails(os.environ.get("ADMIN_EMAIL", ""))

    # Public base URL, used to build the OAuth redirect URI.
    BASE_URL = os.environ.get("BASE_URL", "http://localhost:8000").rstrip("/")

    # --- Persistent login ---------------------------------------------------
    # Keep users signed in until they explicitly log out. Flask-Login issues a
    # long-lived "remember me" cookie that re-establishes the session even after
    # the browser/PWA drops its session cookie (which is what forces re-login on
    # mobile after a few hours in the background).
    REMEMBER_COOKIE_DURATION = timedelta(
        days=int(os.environ.get("LOGIN_DAYS", "365"))
    )
    # Make the session itself long-lived too, so it doesn't die on browser close.
    PERMANENT_SESSION_LIFETIME = REMEMBER_COOKIE_DURATION
    # Refresh the remember cookie on each visit so an active user never expires.
    REMEMBER_COOKIE_REFRESH_EACH_REQUEST = True
    # Harden both cookies. Secure only when served over HTTPS.
    _secure_cookies = BASE_URL.startswith("https://")
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"
    SESSION_COOKIE_SECURE = _secure_cookies
    REMEMBER_COOKIE_HTTPONLY = True
    REMEMBER_COOKIE_SAMESITE = "Lax"
    REMEMBER_COOKIE_SECURE = _secure_cookies

    # Opt-in local login (no Google) to verify flows during development.
    ALLOW_DEV_LOGIN = _bool(os.environ.get("ALLOW_DEV_LOGIN"), default=False)

    # Where JSON data files live.
    STORAGE_DIR = os.environ.get(
        "STORAGE_DIR",
        os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "storage"),
    )

    @property
    def google_configured(self):
        return bool(self.GOOGLE_CLIENT_ID and self.GOOGLE_CLIENT_SECRET)
