# app/schemas/syndarix/agent_type.py
"""
Pydantic schemas for AgentType entity.
"""

import re
from datetime import datetime
from typing import Any
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, field_validator


class AgentTypeBase(BaseModel):
    """Base agent type schema with common fields."""

    name: str = Field(..., min_length=1, max_length=255)
    slug: str | None = Field(None, min_length=1, max_length=255)
    description: str | None = None
    expertise: list[str] = Field(default_factory=list)
    personality_prompt: str = Field(..., min_length=1)
    primary_model: str = Field(..., min_length=1, max_length=100)
    fallback_models: list[str] = Field(default_factory=list)
    model_params: dict[str, Any] = Field(default_factory=dict)
    mcp_servers: list[str] = Field(default_factory=list)
    tool_permissions: dict[str, Any] = Field(default_factory=dict)
    is_active: bool = True

    @field_validator("slug")
    @classmethod
    def validate_slug(cls, v: str | None) -> str | None:
        """Validate slug format: lowercase, alphanumeric, hyphens only."""
        if v is None:
            return v
        if not re.match(r"^[a-z0-9-]+$", v):
            raise ValueError(
                "Slug must contain only lowercase letters, numbers, and hyphens"
            )
        if v.startswith("-") or v.endswith("-"):
            raise ValueError("Slug cannot start or end with a hyphen")
        if "--" in v:
            raise ValueError("Slug cannot contain consecutive hyphens")
        return v

    @field_validator("name")
    @classmethod
    def validate_name(cls, v: str) -> str:
        """Validate agent type name."""
        if not v or v.strip() == "":
            raise ValueError("Agent type name cannot be empty")
        return v.strip()

    @field_validator("expertise")
    @classmethod
    def validate_expertise(cls, v: list[str]) -> list[str]:
        """Validate and normalize expertise list."""
        return [e.strip().lower() for e in v if e.strip()]

    @field_validator("mcp_servers")
    @classmethod
    def validate_mcp_servers(cls, v: list[str]) -> list[str]:
        """Validate MCP server list."""
        return [s.strip() for s in v if s.strip()]


class AgentTypeCreate(AgentTypeBase):
    """Schema for creating a new agent type."""

    name: str = Field(..., min_length=1, max_length=255)
    slug: str = Field(..., min_length=1, max_length=255)
    personality_prompt: str = Field(..., min_length=1)
    primary_model: str = Field(..., min_length=1, max_length=100)


class AgentTypeUpdate(BaseModel):
    """Schema for updating an agent type."""

    name: str | None = Field(None, min_length=1, max_length=255)
    slug: str | None = Field(None, min_length=1, max_length=255)
    description: str | None = None
    expertise: list[str] | None = None
    personality_prompt: str | None = None
    primary_model: str | None = Field(None, min_length=1, max_length=100)
    fallback_models: list[str] | None = None
    model_params: dict[str, Any] | None = None
    mcp_servers: list[str] | None = None
    tool_permissions: dict[str, Any] | None = None
    is_active: bool | None = None

    @field_validator("slug")
    @classmethod
    def validate_slug(cls, v: str | None) -> str | None:
        """Validate slug format."""
        if v is None:
            return v
        if not re.match(r"^[a-z0-9-]+$", v):
            raise ValueError(
                "Slug must contain only lowercase letters, numbers, and hyphens"
            )
        if v.startswith("-") or v.endswith("-"):
            raise ValueError("Slug cannot start or end with a hyphen")
        if "--" in v:
            raise ValueError("Slug cannot contain consecutive hyphens")
        return v

    @field_validator("name")
    @classmethod
    def validate_name(cls, v: str | None) -> str | None:
        """Validate agent type name."""
        if v is not None and (not v or v.strip() == ""):
            raise ValueError("Agent type name cannot be empty")
        return v.strip() if v else v

    @field_validator("expertise")
    @classmethod
    def validate_expertise(cls, v: list[str] | None) -> list[str] | None:
        """Validate and normalize expertise list."""
        if v is None:
            return v
        return [e.strip().lower() for e in v if e.strip()]


class AgentTypeInDB(AgentTypeBase):
    """Schema for agent type in database."""

    id: UUID
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class AgentTypeResponse(AgentTypeBase):
    """Schema for agent type API responses."""

    id: UUID
    created_at: datetime
    updated_at: datetime
    instance_count: int | None = 0

    model_config = ConfigDict(from_attributes=True)


class AgentTypeListResponse(BaseModel):
    """Schema for paginated agent type list responses."""

    agent_types: list[AgentTypeResponse]
    total: int
    page: int
    page_size: int
    pages: int
