"""Runtime configuration for the SDD MCP server.

Provides testable defaults with environment variable overrides for:
- Workspace paths
- Transport options (STDIO/HTTP)
- Logging configuration
"""

import importlib.resources
import os
from pathlib import Path
from typing import Literal

TransportType = Literal["stdio", "http"]


def _get_default_prompts_dir() -> Path:
    """Get the default prompts directory path.

    When running from source, uses project root prompts directory.
    When installed as a package, falls back to mcp_server/prompts.
    """
    # First try project root prompts directory (for development)
    project_root_prompts = Path(__file__).resolve().parents[1] / "prompts"
    if project_root_prompts.exists():
        return project_root_prompts

    # Fallback to mcp_server/prompts (for installed packages)
    try:
        package_anchor = importlib.resources.files("mcp_server")
        prompts_resource = package_anchor / "prompts"
        if prompts_resource.is_dir():
            return Path(str(prompts_resource))
    except (ModuleNotFoundError, AttributeError, ValueError):
        pass

    # Final fallback: mcp_server/prompts relative to this file
    return Path(__file__).parent / "prompts"


class Config:
    """Runtime configuration with environment overrides."""

    def __init__(self) -> None:
        """Initialize configuration with defaults and environment overrides."""
        # Workspace paths
        self.workspace_root = Path(os.getenv("SDD_WORKSPACE_ROOT", "/workspace")).resolve()
        self.prompts_dir = Path(
            os.getenv("SDD_PROMPTS_DIR", str(_get_default_prompts_dir()))
        ).resolve()

        # Transport configuration
        self.transport: TransportType = os.getenv("SDD_TRANSPORT", "stdio")  # type: ignore
        self.http_host = os.getenv("SDD_HTTP_HOST", "0.0.0.0")
        port_str = os.getenv("SDD_HTTP_PORT", "8000")
        try:
            self.http_port = int(port_str)
            if not 1 <= self.http_port <= 65535:
                raise ValueError(f"Port must be between 1 and 65535, got {self.http_port}")
        except ValueError as exc:
            raise ValueError(f"Invalid SDD_HTTP_PORT value '{port_str}': {exc}") from exc

        # Logging configuration
        self.log_level = os.getenv("SDD_LOG_LEVEL", "INFO")
        self.log_format = os.getenv("SDD_LOG_FORMAT", "json")  # json or text

        # CORS configuration for HTTP transport
        self.cors_enabled = os.getenv("SDD_CORS_ENABLED", "true").lower() == "true"
        self.cors_origins = [
            origin.strip()
            for origin in os.getenv("SDD_CORS_ORIGINS", "*").split(",")
            if origin.strip()
        ]

    def ensure_workspace_dirs(self) -> None:
        """Create workspace directories if they don't exist."""
        self.workspace_root.mkdir(parents=True, exist_ok=True)
        (self.workspace_root / "specs").mkdir(exist_ok=True)
        (self.workspace_root / "tasks").mkdir(exist_ok=True)

    def __repr__(self) -> str:
        """Return string representation of configuration."""
        return (
            f"Config(workspace_root={self.workspace_root}, "
            f"prompts_dir={self.prompts_dir}, "
            f"transport={self.transport}, "
            f"http_host={self.http_host}, "
            f"http_port={self.http_port}, "
            f"log_level={self.log_level})"
        )


# Global configuration instance
config = Config()
