from __future__ import annotations

from pathlib import Path
from typing import Any

from openclaw_lite.skills.builder import create_skill, update_skill
from openclaw_lite.skills.runtime import SkillRegistry


def list_skills(registry: SkillRegistry) -> dict[str, Any]:
    return {
        "skills": [
            {
                "name": status.name,
                "enabled": status.enabled,
                "fingerprint": status.fingerprint,
                "error": status.error,
            }
            for status in registry.list_status()
        ]
    }


def reload_skills(registry: SkillRegistry, *, context: dict[str, Any] | None = None) -> dict[str, Any]:
    summary = registry.reload(context=context)
    return {
        "loaded": summary.loaded,
        "reloaded": summary.reloaded,
        "removed": summary.removed,
        "failed": summary.failed,
    }


def create_skill_tool(
    registry: SkillRegistry,
    *,
    name: str,
    description: str,
    instructions: str | None = None,
    entrypoint_code: str | None = None,
    with_entrypoint: bool = True,
) -> dict[str, Any]:
    skill_dir = create_skill(
        registry.root,
        name=name,
        description=description,
        instructions=instructions,
        entrypoint_code=entrypoint_code,
        with_entrypoint=with_entrypoint,
    )
    summary = registry.reload()
    return {
        "skill_dir": str(skill_dir),
        "reload": {
            "loaded": summary.loaded,
            "reloaded": summary.reloaded,
            "removed": summary.removed,
            "failed": summary.failed,
        },
    }


def update_skill_tool(
    registry: SkillRegistry,
    *,
    name: str,
    description: str | None = None,
    instructions: str | None = None,
    entrypoint_code: str | None = None,
    manifest_updates: dict[str, Any] | None = None,
) -> dict[str, Any]:
    skill_dir = Path(registry.root) / name
    result = update_skill(
        skill_dir,
        description=description,
        instructions=instructions,
        entrypoint_code=entrypoint_code,
        manifest_updates=manifest_updates,
    )
    summary = registry.reload()
    return {
        "skill_dir": str(result["skill_dir"]),
        "backup_dir": str(result["backup_dir"]) if result["backup_dir"] else None,
        "reload": {
            "loaded": summary.loaded,
            "reloaded": summary.reloaded,
            "removed": summary.removed,
            "failed": summary.failed,
        },
    }
