"""
Roneia Client - Skill 状态存储

管理本地 Skill 的安装/启用/禁用状态。
"""

import json
import logging
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional
from enum import Enum


logger = logging.getLogger(__name__)


class SkillStatus(str, Enum):
    """Skill 状态"""
    NOT_INSTALLED = "not_installed"  # 未安装
    INSTALLED = "installed"          # 已安装但未启用
    ENABLED = "enabled"              # 已启用


@dataclass
class InstalledSkill:
    """已安装的 Skill"""
    name: str
    """Skill 名称"""

    version: str
    """版本号"""

    title: str
    """显示名称"""

    description: str
    """描述"""

    enabled: bool = False
    """是否启用"""

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return asdict(self)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "InstalledSkill":
        """从字典创建"""
        return cls(
            name=data.get("name", ""),
            version=data.get("version", ""),
            title=data.get("title", ""),
            description=data.get("description", ""),
            enabled=data.get("enabled", False),
        )


class SkillStore:
    """
    Skill 状态存储

    管理本地 Skill 的安装/启用/禁用状态。
    数据持久化到 ~/.roneia/skills.json
    """

    def __init__(self, storage_path: Optional[Path] = None):
        """
        初始化 Skill 存储

        Args:
            storage_path: 存储路径（默认 ~/.roneia/skills.json）
        """
        if storage_path is None:
            storage_path = Path.home() / ".roneia" / "skills.json"

        self._storage_path = storage_path
        self._skills: Dict[str, InstalledSkill] = {}
        self._loaded = False

    def load(self) -> None:
        """加载 Skill 状态"""
        if self._loaded:
            return

        if self._storage_path.exists():
            try:
                with open(self._storage_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    for skill_data in data.get("skills", []):
                        skill = InstalledSkill.from_dict(skill_data)
                        self._skills[skill.name] = skill
                logger.info(f"Loaded {len(self._skills)} skills from {self._storage_path}")
            except Exception as e:
                logger.error(f"Failed to load skills: {e}")
        else:
            logger.info(f"No skills file found at {self._storage_path}")

        self._loaded = True

    def save(self) -> None:
        """保存 Skill 状态"""
        # 确保目录存在
        self._storage_path.parent.mkdir(parents=True, exist_ok=True)

        data = {
            "skills": [skill.to_dict() for skill in self._skills.values()]
        }

        try:
            with open(self._storage_path, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            logger.debug(f"Saved {len(self._skills)} skills to {self._storage_path}")
        except Exception as e:
            logger.error(f"Failed to save skills: {e}")

    def install(
        self,
        name: str,
        version: str,
        title: str,
        description: str,
    ) -> bool:
        """
        安装 Skill

        Args:
            name: Skill 名称
            version: 版本号
            title: 显示名称
            description: 描述

        Returns:
            是否安装成功
        """
        self.load()

        if name in self._skills:
            # 已安装，更新信息
            skill = self._skills[name]
            skill.version = version
            skill.title = title
            skill.description = description
            logger.info(f"Updated skill: {name}")
        else:
            # 新安装
            self._skills[name] = InstalledSkill(
                name=name,
                version=version,
                title=title,
                description=description,
                enabled=False,
            )
            logger.info(f"Installed skill: {name}")

        self.save()
        return True

    def remove(self, name: str) -> bool:
        """
        删除 Skill

        Args:
            name: Skill 名称

        Returns:
            是否删除成功
        """
        self.load()

        if name not in self._skills:
            return False

        del self._skills[name]
        self.save()
        logger.info(f"Removed skill: {name}")
        return True

    def enable(self, name: str) -> bool:
        """
        启用 Skill

        Args:
            name: Skill 名称

        Returns:
            是否启用成功
        """
        self.load()

        if name not in self._skills:
            return False

        self._skills[name].enabled = True
        self.save()
        logger.info(f"Enabled skill: {name}")
        return True

    def disable(self, name: str) -> bool:
        """
        禁用 Skill

        Args:
            name: Skill 名称

        Returns:
            是否禁用成功
        """
        self.load()

        if name not in self._skills:
            return False

        self._skills[name].enabled = False
        self.save()
        logger.info(f"Disabled skill: {name}")
        return True

    def get(self, name: str) -> Optional[InstalledSkill]:
        """
        获取 Skill

        Args:
            name: Skill 名称

        Returns:
            Skill 信息，不存在返回 None
        """
        self.load()
        return self._skills.get(name)

    def get_status(self, name: str) -> SkillStatus:
        """
        获取 Skill 状态

        Args:
            name: Skill 名称

        Returns:
            Skill 状态
        """
        self.load()
        skill = self._skills.get(name)
        if skill is None:
            return SkillStatus.NOT_INSTALLED
        return SkillStatus.ENABLED if skill.enabled else SkillStatus.INSTALLED

    def list_installed(self) -> List[InstalledSkill]:
        """
        列出已安装的 Skill

        Returns:
            已安装的 Skill 列表
        """
        self.load()
        return list(self._skills.values())

    def list_enabled(self) -> List[InstalledSkill]:
        """
        列出已启用的 Skill

        Returns:
            已启用的 Skill 列表
        """
        self.load()
        return [skill for skill in self._skills.values() if skill.enabled]

    def get_enabled_names(self) -> List[str]:
        """
        获取已启用的 Skill 名称列表

        Returns:
            Skill 名称列表
        """
        return [skill.name for skill in self.list_enabled()]

    def is_installed(self, name: str) -> bool:
        """Skill 是否已安装"""
        self.load()
        return name in self._skills

    def is_enabled(self, name: str) -> bool:
        """Skill 是否已启用"""
        self.load()
        skill = self._skills.get(name)
        return skill is not None and skill.enabled
