"""Configuration and environment variables for MSSQL MCP Server."""

import os


def _parse_bool(value: str, default: bool = False) -> bool:
    """Parse a string value to boolean."""
    if not value:
        return default
    return value.lower() in ("true", "1", "yes")


# Security configuration
READONLY_MODE = _parse_bool(os.getenv("MSSQL_READONLY", "true"), default=True)

# Granular write permission controls (only effective when READONLY_MODE is False)
ALLOW_INSERT = _parse_bool(os.getenv("MSSQL_ALLOW_INSERT", "true"), default=True)
ALLOW_UPDATE = _parse_bool(os.getenv("MSSQL_ALLOW_UPDATE", "true"), default=True)
ALLOW_DELETE = _parse_bool(os.getenv("MSSQL_ALLOW_DELETE", "true"), default=True)
ALLOW_DDL = _parse_bool(os.getenv("MSSQL_ALLOW_DDL", "true"), default=True)  # CREATE, ALTER, DROP
ALLOW_EXEC = _parse_bool(os.getenv("MSSQL_ALLOW_EXEC", "true"), default=True)  # EXEC, EXECUTE

# Database configuration from environment variables
DB_CONFIG = {
    "server": os.getenv("MSSQL_SERVER", "localhost"),
    "database": os.getenv("MSSQL_DATABASE", "master"),
    "user": os.getenv("MSSQL_USER", ""),
    "password": os.getenv("MSSQL_PASSWORD", ""),
    "port": os.getenv("MSSQL_PORT", "1433"),
    "driver": os.getenv("MSSQL_DRIVER", "ODBC Driver 18 for SQL Server"),
    "encrypt": os.getenv("MSSQL_ENCRYPT", "yes"),
    "trust_server_certificate": os.getenv("MSSQL_TRUST_SERVER_CERTIFICATE", "no"),
    "auth_mode": os.getenv("MSSQL_AUTH_MODE", "sql"),  # sql, windows, azure
}

# Statement type categories for granular control
INSERT_STATEMENTS = {"INSERT", "MERGE"}
UPDATE_STATEMENTS = {"UPDATE"}
DELETE_STATEMENTS = {"DELETE", "TRUNCATE"}
DDL_STATEMENTS = {"CREATE", "ALTER", "DROP", "GRANT", "REVOKE", "DENY"}
EXEC_STATEMENTS = {"EXEC", "EXECUTE"}

# All blocked statement types when in full readonly mode
BLOCKED_STATEMENT_TYPES = (
    INSERT_STATEMENTS | UPDATE_STATEMENTS | DELETE_STATEMENTS | DDL_STATEMENTS | EXEC_STATEMENTS
)


def is_readonly() -> bool:
    """Check if the server is in read-only mode."""
    return READONLY_MODE


def is_insert_allowed() -> bool:
    """Check if INSERT operations are allowed."""
    return not READONLY_MODE and ALLOW_INSERT


def is_update_allowed() -> bool:
    """Check if UPDATE operations are allowed."""
    return not READONLY_MODE and ALLOW_UPDATE


def is_delete_allowed() -> bool:
    """Check if DELETE operations are allowed."""
    return not READONLY_MODE and ALLOW_DELETE


def is_ddl_allowed() -> bool:
    """Check if DDL operations (CREATE, ALTER, DROP) are allowed."""
    return not READONLY_MODE and ALLOW_DDL


def is_exec_allowed() -> bool:
    """Check if EXEC/EXECUTE operations are allowed."""
    return not READONLY_MODE and ALLOW_EXEC


def get_blocked_statements() -> set[str]:
    """Get the set of currently blocked statement types based on configuration."""
    if READONLY_MODE:
        return BLOCKED_STATEMENT_TYPES.copy()

    blocked = set()
    if not ALLOW_INSERT:
        blocked.update(INSERT_STATEMENTS)
    if not ALLOW_UPDATE:
        blocked.update(UPDATE_STATEMENTS)
    if not ALLOW_DELETE:
        blocked.update(DELETE_STATEMENTS)
    if not ALLOW_DDL:
        blocked.update(DDL_STATEMENTS)
    if not ALLOW_EXEC:
        blocked.update(EXEC_STATEMENTS)

    return blocked


def get_permission_summary() -> dict:
    """Get a summary of current permission settings."""
    return {
        "readonly_mode": READONLY_MODE,
        "allow_insert": is_insert_allowed(),
        "allow_update": is_update_allowed(),
        "allow_delete": is_delete_allowed(),
        "allow_ddl": is_ddl_allowed(),
        "allow_exec": is_exec_allowed(),
        "blocked_statements": list(get_blocked_statements()),
    }
