import os
import secrets

BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
MATOMO_DEFAULT_BASE_URL = "https://analytics.investment-nieruchomosci.com/"


def _bool_env(name: str, default: bool = False) -> bool:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default
    return raw_value.strip().lower() in {"1", "true", "yes", "on"}


def _int_env(name: str, default: int) -> int:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default
    try:
        return int(raw_value)
    except ValueError:
        return default


def _optional_positive_int_env(name: str, default: int | None) -> int | None:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default

    normalized = raw_value.strip().lower()
    if normalized in {"", "0", "false", "none", "off", "disable", "disabled"}:
        return None

    try:
        value = int(raw_value)
    except ValueError:
        return default

    return value if value > 0 else None


def _choice_env(name: str, choices: set[str], default: str) -> str:
    raw_value = os.getenv(name)
    if raw_value is None:
        return default
    normalized = raw_value.strip().lower()
    return normalized if normalized in choices else default


class BaseConfig:
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"

    # logika wspolna
    JSON_SORT_KEYS = False


def db_shell_password() -> str:
    """DB Shell unlock password, read from the environment on every call (no cache).
    No default: unset or empty means "" so the unlock stays disabled (fail closed)."""
    return os.environ.get('DB_SHELL_PASSWORD', '')


def matomo_reporting_token() -> str:
    """Server-only Reporting API credential; never copied into Flask template config."""
    return os.environ.get("MATOMO_REPORTING_TOKEN", "")


def env_config() -> dict:
    """Environment-backed settings, read when create_app() runs (after .env
    has been loaded), never at import time."""
    # Staly klucz z ENV; fallback tylko poza produkcja.
    secret_key = os.getenv("SECRET_KEY")
    if not secret_key:
        if os.getenv("FLASK_ENV", "development") == "production":
            raise RuntimeError("Brak SECRET_KEY w zmiennych srodowiskowych.")
        secret_key = secrets.token_hex(32)

    flask_env = os.getenv("FLASK_ENV", "development")
    matomo_base_url = os.getenv("MATOMO_BASE_URL", MATOMO_DEFAULT_BASE_URL).strip()
    if not matomo_base_url:
        matomo_base_url = MATOMO_DEFAULT_BASE_URL
    if not matomo_base_url.endswith("/"):
        matomo_base_url += "/"

    return {
        "SECRET_KEY": secret_key,
        # Fail closed: an explicit flag is not enough outside the one known
        # production environment. Unknown FLASK_ENV values must never turn
        # analytics on accidentally.
        "MATOMO_ENABLED": flask_env == "production" and _bool_env("MATOMO_ENABLED", False),
        "MATOMO_BASE_URL": matomo_base_url,
        "MATOMO_SITE_ID": _int_env("MATOMO_SITE_ID", 1),
        "MATOMO_OFFER_DIMENSION_ID": _optional_positive_int_env("MATOMO_OFFER_DIMENSION_ID", None),
        "MATOMO_REPORTING_ENABLED": flask_env == "production" and _bool_env("MATOMO_REPORTING_ENABLED", False),
        "MATOMO_REPORTING_START_DATE": os.getenv("MATOMO_REPORTING_START_DATE", "").strip(),
        # Report-only is deliberately the safe default: production operators
        # inspect aggregate candidate counts before explicitly choosing enforce.
        "PLATFORM_LOG_RETENTION_MODE": _choice_env(
            "PLATFORM_LOG_RETENTION_MODE", {"report", "enforce", "off"}, "report"
        ),
        "RATELIMIT_STORAGE_URI": os.getenv("RATELIMIT_STORAGE_URI", "memory://"),
        "FRANCHISE_MEETING_AGENT_ID": _int_env("FRANCHISE_MEETING_AGENT_ID", 101),
        "FRANCHISE_MEETING_SLOT_MINUTES": _int_env("FRANCHISE_MEETING_SLOT_MINUTES", 60),
        "FRANCHISE_MEETING_WINDOW_DAYS": _int_env("FRANCHISE_MEETING_WINDOW_DAYS", 21),
        "FRANCHISE_MEETING_WORKDAY_START_HOUR": _int_env("FRANCHISE_MEETING_WORKDAY_START_HOUR", 9),
        "FRANCHISE_MEETING_WORKDAY_END_HOUR": _int_env("FRANCHISE_MEETING_WORKDAY_END_HOUR", 17),
    }


class DevConfig(BaseConfig):
    DEBUG = True
    SESSION_COOKIE_SECURE = False


class ProdConfig(BaseConfig):
    DEBUG = False
    SESSION_COOKIE_SECURE = True
