from __future__ import annotations

import os
from functools import lru_cache
from pathlib import Path

STORAGE_BACKENDS = {"file", "db"}
DEFAULT_MCP_ALLOWED_HOSTS = ("127.0.0.1:*", "localhost:*", "[::1]:*")
DEFAULT_MCP_ALLOWED_ORIGINS = (
    "http://127.0.0.1:*",
    "http://localhost:*",
    "http://[::1]:*",
)


class Settings:
    def __init__(
        self,
        repo_root: Path | None = None,
        database_url: str | None = None,
        storage_backend: str | None = None,
    ) -> None:
        configured_root = repo_root or os.environ.get("GNEXUS_BOOK_REPO_ROOT")
        self.repo_root = (
            Path(configured_root).expanduser().resolve()
            if configured_root
            else Path(__file__).resolve().parents[2]
        )
        self.docs_extensions = {".md"}
        self.inventory_dir = self.repo_root / "40-inventory"
        self.generated_dir = self.repo_root / "60-generated"

        backend = (storage_backend or os.environ.get("GNEXUS_BOOK_STORAGE_BACKEND", "file")).lower()
        if backend not in STORAGE_BACKENDS:
            raise ValueError(
                f"GNEXUS_BOOK_STORAGE_BACKEND must be one of {sorted(STORAGE_BACKENDS)}, got {backend!r}"
            )
        self.storage_backend = backend
        self.database_url = database_url or os.environ.get("GNEXUS_BOOK_DATABASE_URL")

        self.auth_client_id = os.environ.get("GNEXUS_BOOK_AUTH_CLIENT_ID")
        self.auth_client_secret = os.environ.get("GNEXUS_BOOK_AUTH_CLIENT_SECRET")
        self.auth_base_url = os.environ.get("GNEXUS_BOOK_AUTH_BASE_URL")
        self.auth_redirect_uri = os.environ.get("GNEXUS_BOOK_AUTH_REDIRECT_URI")
        self.auth_webhook_secret = os.environ.get("GNEXUS_BOOK_AUTH_WEBHOOK_SECRET")
        self.auth_session_cookie = os.environ.get(
            "GNEXUS_BOOK_AUTH_SESSION_COOKIE", "gnb_session"
        )
        self.auth_state_cookie = os.environ.get(
            "GNEXUS_BOOK_AUTH_STATE_COOKIE", "gnb_oauth_state"
        )
        self.auth_session_ttl_seconds = int(
            os.environ.get("GNEXUS_BOOK_AUTH_SESSION_TTL_SECONDS", str(7 * 24 * 3600))
        )
        self.auth_state_ttl_seconds = int(
            os.environ.get("GNEXUS_BOOK_AUTH_STATE_TTL_SECONDS", "300")
        )
        self.auth_webhook_tolerance_seconds = int(
            os.environ.get("GNEXUS_BOOK_AUTH_WEBHOOK_TOLERANCE_SECONDS", "300")
        )
        self.auth_scopes = tuple(
            os.environ.get(
                "GNEXUS_BOOK_AUTH_SCOPES",
                "openid email profile roles permissions",
            ).split()
        )
        secure_default = "true" if (self.auth_redirect_uri or "").startswith("https://") else "false"
        self.auth_cookie_secure = os.environ.get(
            "GNEXUS_BOOK_AUTH_COOKIE_SECURE", secure_default
        ).lower() in {"1", "true", "yes", "on"}

        self.mcp_host = os.environ.get("GNEXUS_BOOK_MCP_HOST", "0.0.0.0")
        self.mcp_port = int(os.environ.get("GNEXUS_BOOK_MCP_PORT", "8001"))
        self.mcp_static_token = os.environ.get("GNEXUS_BOOK_MCP_TOKEN")
        self.mcp_key_rate_limit = int(
            os.environ.get("GNEXUS_BOOK_MCP_KEY_RATE_LIMIT", "30")
        )
        self.mcp_request_rate_limit = int(
            os.environ.get("GNEXUS_BOOK_MCP_REQUEST_RATE_LIMIT", "300")
        )
        self.mcp_allowed_hosts = tuple(
            item.strip()
            for item in os.environ.get(
                "GNEXUS_BOOK_MCP_ALLOWED_HOSTS",
                ",".join(DEFAULT_MCP_ALLOWED_HOSTS),
            ).split(",")
            if item.strip()
        ) or DEFAULT_MCP_ALLOWED_HOSTS
        self.mcp_allowed_origins = tuple(
            item.strip()
            for item in os.environ.get(
                "GNEXUS_BOOK_MCP_ALLOWED_ORIGINS",
                ",".join(DEFAULT_MCP_ALLOWED_ORIGINS),
            ).split(",")
            if item.strip()
        ) or DEFAULT_MCP_ALLOWED_ORIGINS
        self.internal_key_secret = os.environ.get("GNEXUS_BOOK_INTERNAL_KEY_SECRET")
        self.internal_allowlist = tuple(
            item.strip()
            for item in os.environ.get("GNEXUS_BOOK_INTERNAL_ALLOWLIST", "").split(",")
            if item.strip()
        )
        self.internal_rate_limit = int(
            os.environ.get("GNEXUS_BOOK_INTERNAL_RATE_LIMIT", "60")
        )

    @property
    def auth_enabled(self) -> bool:
        return bool(
            self.auth_client_id
            and self.auth_client_secret
            and self.auth_base_url
            and self.auth_redirect_uri
        )


@lru_cache
def get_settings() -> Settings:
    return Settings()
