"""
Agent manifest metadata models.

Defines identity and versioning information for agents.
"""

from pydantic import BaseModel, Field, field_validator

from aphub_sdk.schemas.constants import (
    AGENT_NAME_MAX_LENGTH,
    AGENT_NAME_MIN_LENGTH,
    AGENT_NAME_PATTERN,
    VERSION_PATTERN,
)

import re
from typing import Optional


class Maintainer(BaseModel):
    """Agent maintainer information."""

    name: str = Field(..., description="Maintainer name")
    email: Optional[str] = Field(None, description="Maintainer email")
    url: Optional[str] = Field(None, description="Maintainer URL (e.g., GitHub profile)")


class Repository(BaseModel):
    """Source repository information."""

    type: str = Field("git", description="Repository type")
    url: str = Field(..., description="Repository URL")


class AgentMetadata(BaseModel):
    """
    Agent metadata block.

    Contains identity, versioning, and descriptive information.
    """

    # Required fields
    name: str = Field(
        ...,
        min_length=AGENT_NAME_MIN_LENGTH,
        max_length=AGENT_NAME_MAX_LENGTH,
        description="Unique agent identifier",
    )
    version: str = Field(..., description="Semantic version (e.g., 1.0.0)")

    # Optional identity fields
    namespace: Optional[str] = Field(None, description="Organization/team namespace")
    display_name: Optional[str] = Field(None, description="Human-readable name")
    description: Optional[str] = Field(None, description="Agent description (markdown supported)")

    # Contact information
    maintainers: list[Maintainer] = Field(default_factory=list, description="Agent maintainers")

    # Licensing
    license: Optional[str] = Field(None, description="License identifier (e.g., MIT, Apache-2.0)")

    # Repository link
    repository: Optional[Repository] = Field(None, description="Source repository")

    # Documentation
    documentation: Optional[str] = Field(None, description="Documentation URL")

    # Keywords for search
    keywords: list[str] = Field(default_factory=list, description="Search keywords")

    @field_validator("name")
    @classmethod
    def validate_name(cls, value: str) -> str:
        """Validate agent name format."""
        if not re.match(AGENT_NAME_PATTERN, value):
            raise ValueError(
                f"Agent name must match pattern {AGENT_NAME_PATTERN}: "
                "lowercase alphanumeric with hyphens/underscores, "
                "must start and end with alphanumeric"
            )
        return value

    @field_validator("version")
    @classmethod
    def validate_version(cls, value: str) -> str:
        """Validate semantic version format."""
        if not re.match(VERSION_PATTERN, value):
            raise ValueError(
                f"Version must follow semantic versioning (e.g., 1.0.0, 1.0.0-alpha): {value}"
            )
        return value
