"""Configuration loaded from environment variables."""

import os
from enum import Enum


class Mode(str, Enum):
    READ = "read"
    TRADE = "trade"
    FULL = "full"


# Permission hierarchy: which modes allow which permission levels
MODE_PERMISSIONS: dict[Mode, set[str]] = {
    Mode.READ: {"read"},
    Mode.TRADE: {"read", "trade"},
    Mode.FULL: {"read", "trade", "full"},
}


def get_mode() -> Mode:
    """Get permission mode. Checks SQLite first (remote mode), then env var."""
    db_path = get_db_path()
    if db_path and os.path.exists(db_path):
        try:
            from bybit_mcp_server.auth.db import load_bybit_credentials

            creds = load_bybit_credentials(db_path)
            if creds and creds.get("mode"):
                return Mode(creds["mode"])
        except Exception:
            pass
    raw = os.getenv("BYBIT_MODE", "read").lower()
    try:
        return Mode(raw)
    except ValueError:
        return Mode.READ


def get_testnet() -> bool:
    return os.getenv("BYBIT_TESTNET", "true").lower() == "true"


def get_api_key() -> str | None:
    key = os.getenv("BYBIT_API_KEY", "")
    return key or None


def get_api_secret() -> str | None:
    secret = os.getenv("BYBIT_API_SECRET", "")
    return secret or None


def get_recv_window() -> int | None:
    raw = os.getenv("BYBIT_RECV_WINDOW", "")
    return int(raw) if raw else None


# --- Transport configuration ---


def get_transport() -> str:
    """Get transport type: 'stdio' (default, local) or 'streamable-http' (remote)."""
    return os.getenv("BYBIT_MCP_TRANSPORT", "stdio")


def get_host() -> str:
    """Get host to bind for HTTP transport."""
    return os.getenv("BYBIT_MCP_HOST", "0.0.0.0")


def get_port() -> int:
    """Get port to bind for HTTP transport."""
    return int(os.getenv("BYBIT_MCP_PORT", "8000"))


# --- Auth configuration (remote mode only) ---


def get_auth_enabled() -> bool:
    """Auth is enabled when admin username AND issuer URL are both set."""
    return bool(os.getenv("BYBIT_MCP_ADMIN_USERNAME")) and bool(os.getenv("BYBIT_MCP_ISSUER_URL"))


def get_admin_username() -> str:
    return os.getenv("BYBIT_MCP_ADMIN_USERNAME", "")


def get_admin_password() -> str:
    return os.getenv("BYBIT_MCP_ADMIN_PASSWORD", "")


def get_secret_key() -> str:
    """Fernet-compatible key for encrypting Bybit API credentials at rest."""
    return os.getenv("BYBIT_MCP_SECRET_KEY", "")


def get_issuer_url() -> str:
    """OAuth issuer URL (the public-facing URL of this server)."""
    return os.getenv("BYBIT_MCP_ISSUER_URL", "http://localhost:8000")


def get_db_path() -> str:
    """Path to SQLite database file."""
    return os.getenv("BYBIT_MCP_DB_PATH", "./bybit_mcp.db")
