"""Skill API client."""

from __future__ import annotations

from typing import Any

from manta_client.api.client import MantaClient, get_client


class SkillAPI:
    """Skill API client."""

    def __init__(self, client: MantaClient | None = None):
        self.client = client or get_client()

    async def list_skills(self, skip: int = 0, limit: int = 100) -> dict[str, Any]:
        """List skills."""
        return await self.client.get("/api/v1/skills", params={"skip": skip, "limit": limit})

    async def get_skill(self, slug: str) -> dict[str, Any]:
        """Get skill by slug."""
        return await self.client.get(f"/api/v1/skills/{slug}")

    async def create_skill(self, data: dict[str, Any]) -> dict[str, Any]:
        """Create or sync a skill."""
        return await self.client.post("/api/v1/skills", data=data)

    async def update_skill(self, slug: str, data: dict[str, Any]) -> dict[str, Any]:
        """Update skill metadata (and optionally re-sync via tag)."""
        return await self.client.put(f"/api/v1/skills/{slug}", data=data)

    async def upload_skill(
        self,
        archive_bytes: bytes,
        source_repo: str,
        source_path: str,
        tag: str | None = None,
    ) -> dict[str, Any]:
        """Upload a locally-fetched skill archive."""
        fields: dict[str, str] = {
            "source_repo": source_repo,
            "source_path": source_path,
        }
        if tag:
            fields["tag"] = tag
        return await self.client.upload(
            "/api/v1/skills/upload",
            file_content=archive_bytes,
            file_name="skill.tar.gz",
            fields=fields,
        )

    async def delete_skill(self, slug: str) -> dict[str, Any]:
        """Delete skill by slug."""
        return await self.client.delete(f"/api/v1/skills/{slug}")

    async def sync_all(self) -> dict[str, Any]:
        """Sync all skills (async, returns task_id)."""
        return await self.client.post("/api/v1/skills/sync")

    async def import_repo(self, data: dict[str, Any]) -> dict[str, Any]:
        """Import skills from repo (async, returns task_id)."""
        return await self.client.post("/api/v1/skills/import", data=data)


_skill_api: SkillAPI | None = None


def get_skill_api() -> SkillAPI:
    """Get or create the global Skill API instance."""
    global _skill_api
    if _skill_api is None:
        _skill_api = SkillAPI()
    return _skill_api
