"""Configuration models for Portal."""

from __future__ import annotations

from typing import Any

from pydantic import BaseModel, Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class ColorSettings(BaseModel):
    """Color configuration settings."""

    enabled: bool = Field(True, description="Enable color coding")
    sync_iterm: bool = Field(True, description="Sync colors with iTerm")
    sync_cursor: bool = Field(True, description="Sync colors with Cursor")
    sync_claude: bool = Field(True, description="Sync colors with Claude")
    high_contrast: bool = Field(False, description="Use high-contrast palette")

    model_config = {"extra": "forbid"}


class EditorSettings(BaseModel):
    """Editor configuration settings."""

    default: str = Field("cursor", description="Default editor to use")
    cursor: dict[str, Any] = Field(default_factory=dict, description="Cursor-specific settings")
    vscode: dict[str, Any] = Field(default_factory=dict, description="VSCode-specific settings")
    auto_open: bool = Field(True, description="Automatically open editor after creation")

    model_config = {"extra": "forbid"}


class ShellSettings(BaseModel):
    """Shell integration settings."""

    completions_enabled: bool = Field(True, description="Enable shell completions")
    cd_function: bool = Field(True, description="Install 'portal cd' shell function")
    prompt_integration: bool = Field(False, description="Show worktree in prompt")

    model_config = {"extra": "forbid"}


class PortalConfig(BaseSettings):
    """Portal configuration with validation."""

    model_config = SettingsConfigDict(
        env_prefix="PORTAL_",
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",  # Allow extra fields for forward compatibility
    )

    # Core settings
    version: str = Field("1.0", description="Configuration version")
    base_dir: str = Field("../{project}_worktrees", description="Base directory pattern")
    default_base_branch: str = Field("main", description="Default base branch for new worktrees")

    # Feature settings
    colors: ColorSettings = Field(default_factory=ColorSettings)
    editor: EditorSettings = Field(default_factory=EditorSettings)
    shell: ShellSettings = Field(default_factory=ShellSettings)

    # Hook configurations
    hooks: dict[str, list[dict[str, Any]]] = Field(
        default_factory=dict, description="Hook configurations by stage"
    )

    # Template configurations
    templates: dict[str, Any] = Field(default_factory=dict, description="Worktree templates")

    # Branch pattern mappings
    branch_patterns: dict[str, str] = Field(
        default_factory=lambda: {
            "feature/*": "feature",
            "hotfix/*": "hotfix",
            "release/*": "release",
            "bugfix/*": "bugfix",
            "experiment/*": "experiments",
        },
        description="Branch pattern to directory mapping",
    )

    @field_validator("base_dir")
    @classmethod
    def validate_base_dir(cls, v: str) -> str:
        """Ensure base_dir contains project placeholder."""
        if "{project}" not in v:
            raise ValueError("base_dir must contain '{project}' placeholder")
        return v

    @field_validator("version")
    @classmethod
    def validate_version(cls, v: str) -> str:
        """Validate configuration version."""
        supported_versions = ["1.0", "1.1"]
        if v not in supported_versions:
            raise ValueError(f"Unsupported configuration version: {v}")
        return v
