"""
Configuration module for the Pentest MCP Server.
Handles environment variables and default settings.
"""

import os
from typing import Optional
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()


class Config:
    """Configuration class for MCP server settings."""

    # SSH Connection Settings
    TARGET_HOST: str = os.getenv("TARGET_HOST", "localhost")
    TARGET_PORT: int = int(os.getenv("TARGET_PORT", "22"))
    TARGET_USER: str = os.getenv("TARGET_USER", "kali")
    TARGET_PASSWORD: Optional[str] = os.getenv("TARGET_PASSWORD")
    TARGET_SSH_KEY: Optional[str] = os.getenv("TARGET_SSH_KEY")

    # Resource Limits
    MAX_SESSIONS: int = int(os.getenv("MAX_SESSIONS", "20"))
    MAX_HEAVY_TASKS: int = int(os.getenv("MAX_HEAVY_TASKS", "3"))

    # Monitoring Settings
    POLL_INTERVAL: float = float(os.getenv("POLL_INTERVAL", "1.0"))
    DEFAULT_TIMEOUT: int = int(os.getenv("DEFAULT_TIMEOUT", "300"))

    # Reconnection Settings
    MAX_RECONNECT_ATTEMPTS: int = int(os.getenv("MAX_RECONNECT_ATTEMPTS", "5"))
    RECONNECT_DELAY_BASE: int = int(os.getenv("RECONNECT_DELAY_BASE", "2"))

    # Tmux Settings
    TMUX_SOCKET_NAME: str = os.getenv("TMUX_SOCKET_NAME", "pentest-mcp")

    # Heavy Commands (for resource management)
    HEAVY_COMMANDS = [
        "nmap", "masscan", "hydra", "john", 
        "hashcat", "sqlmap", "wfuzz", "gobuster",
        "nikto", "burpsuite", "metasploit"
    ]

    # Security - Blocked Commands (optional safety)
    BLOCKED_COMMANDS = [
        r'rm\s+-rf\s+/',              # Recursive delete from root
        r'dd\s+if=.*of=/dev/sd',      # Disk wiping
        r'mkfs',                       # Format filesystem
        r':(){ :|:& };:',             # Fork bomb
        r'sudo\s+rm\s+-rf\s+/',      # Sudo recursive delete
    ]

    @classmethod
    def validate_config(cls) -> bool:
        """Validate that required configuration is present."""
        if not cls.TARGET_HOST:
            raise ValueError("TARGET_HOST is required")

        if not cls.TARGET_USER:
            raise ValueError("TARGET_USER is required")

        if not cls.TARGET_PASSWORD and not cls.TARGET_SSH_KEY:
            raise ValueError("Either TARGET_PASSWORD or TARGET_SSH_KEY must be provided")

        return True

    @classmethod
    def get_ssh_auth_method(cls) -> dict:
        """Get SSH authentication method based on config."""
        if cls.TARGET_SSH_KEY and os.path.exists(cls.TARGET_SSH_KEY):
            return {"client_keys": [cls.TARGET_SSH_KEY]}
        elif cls.TARGET_PASSWORD:
            return {"password": cls.TARGET_PASSWORD}
        else:
            raise ValueError("No valid authentication method available")
