"""Skill models for the Danube SDK."""

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field


class SkillFile(BaseModel):
    """A file within a skill.

    Skills can contain multiple files including scripts,
    reference documentation, and assets.
    """

    name: str
    content: str = ""
    content_type: Optional[str] = None

    model_config = {"extra": "ignore"}


class Skill(BaseModel):
    """Skill summary for search results.

    Skills are reusable instructions that teach AI agents
    how to perform specific tasks.
    """

    id: str
    name: str
    description: str = ""
    service_id: Optional[str] = None
    metadata: Dict[str, Any] = Field(default_factory=dict)

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "Skill":
        """Create a Skill from API response data.

        Args:
            data: Raw API response dictionary.

        Returns:
            Skill instance.
        """
        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            description=data.get("description", ""),
            service_id=data.get("service_id"),
            metadata=data.get("metadata", {}),
        )


class SkillContent(BaseModel):
    """Full skill with all content.

    Contains the complete skill definition including the main
    SKILL.md content and all associated files.
    """

    id: str
    name: str
    description: str = ""

    # Main content - the SKILL.md file
    skill_md: str = ""

    # Associated files
    scripts: List[SkillFile] = Field(default_factory=list)
    references: List[SkillFile] = Field(default_factory=list)
    assets: List[SkillFile] = Field(default_factory=list)

    # Metadata
    license: Optional[str] = None
    compatibility: Optional[str] = None
    metadata: Dict[str, Any] = Field(default_factory=dict)
    service_id: Optional[str] = None

    model_config = {"extra": "ignore"}

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "SkillContent":
        """Create a SkillContent from API response data.

        Args:
            data: Raw API response dictionary.

        Returns:
            SkillContent instance.
        """
        # Parse file lists
        scripts = [
            SkillFile(**s) if isinstance(s, dict) else SkillFile(name=str(s))
            for s in data.get("scripts", [])
        ]
        references = [
            SkillFile(**r) if isinstance(r, dict) else SkillFile(name=str(r))
            for r in data.get("references", data.get("reference_files", []))
        ]
        assets = [
            SkillFile(**a) if isinstance(a, dict) else SkillFile(name=str(a))
            for a in data.get("assets", [])
        ]

        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            description=data.get("description", ""),
            skill_md=data.get("skill_md", data.get("skill_md_content", "")),
            scripts=scripts,
            references=references,
            assets=assets,
            license=data.get("license"),
            compatibility=data.get("compatibility"),
            metadata=data.get("metadata", {}),
            service_id=data.get("service_id"),
        )

    def get_script(self, name: str) -> Optional[SkillFile]:
        """Get a script file by name.

        Args:
            name: The script filename.

        Returns:
            SkillFile if found, None otherwise.
        """
        for script in self.scripts:
            if script.name == name:
                return script
        return None

    def get_reference(self, name: str) -> Optional[SkillFile]:
        """Get a reference file by name.

        Args:
            name: The reference filename.

        Returns:
            SkillFile if found, None otherwise.
        """
        for ref in self.references:
            if ref.name == name:
                return ref
        return None

    def get_asset(self, name: str) -> Optional[SkillFile]:
        """Get an asset file by name.

        Args:
            name: The asset filename.

        Returns:
            SkillFile if found, None otherwise.
        """
        for asset in self.assets:
            if asset.name == name:
                return asset
        return None
