"""Skills registry — manages skill content and access control."""

import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

import yaml

from .license import License, Tier


@dataclass
class SkillMetadata:
    """Metadata for a registered skill."""
    name: str
    description: str
    tier: Tier
    category: str
    version: str = "1.0.0"
    tags: list[str] = field(default_factory=list)
    content: str = ""


class SkillsRegistry:
    """Registry that manages all ARIS skills with tier-based access control."""

    def __init__(self, skills_dir: str = "./skills") -> None:
        self._skills: dict[str, SkillMetadata] = {}
        self._skills_dir = Path(skills_dir)
        self._load_skills()

    def _load_skills(self) -> None:
        """Load all skills from the skills directory."""
        for tier_dir in ["free", "pro", "shield", "intel"]:
            tier_path = self._skills_dir / tier_dir
            if not tier_path.exists():
                continue
            # Support both flat .md files and subdirs with SKILL.md
            for skill_file in tier_path.rglob("*.md"):
                self._load_skill(skill_file, Tier(tier_dir))
            for skill_file in tier_path.rglob("SKILL.md"):
                self._load_skill(skill_file, Tier(tier_dir))

    def _load_skill(self, path: Path, tier: Tier) -> None:
        """Load a single skill from a markdown file."""
        content = path.read_text()

        # Parse YAML frontmatter
        if content.startswith("---"):
            parts = content.split("---", 2)
            if len(parts) >= 3:
                try:
                    meta = yaml.safe_load(parts[1])
                except yaml.YAMLError:
                    meta = {}
                body = parts[2].strip()
            else:
                meta, body = {}, content
        else:
            meta, body = {}, content

        skill = SkillMetadata(
            name=meta.get("name", path.stem),
            description=meta.get("description", ""),
            tier=tier,
            category=meta.get("category", "general"),
            version=meta.get("version", "1.0.0"),
            tags=meta.get("tags", []),
            content=body,
        )
        self._skills[skill.name] = skill
        # Also index by filename for fallback lookup
        file_key = path.stem if path.stem != "SKILL" else path.parent.name
        if file_key != skill.name:
            self._skills[file_key] = skill

    def list_skills(self, license: Optional[License] = None) -> list[dict]:
        """List available skills, filtered by license access."""
        result = []
        for skill in self._skills.values():
            accessible = license.has_access(skill.tier) if license else skill.tier == Tier.FREE
            result.append({
                "name": skill.name,
                "description": skill.description,
                "tier": skill.tier.value,
                "category": skill.category,
                "version": skill.version,
                "tags": skill.tags,
                "accessible": accessible,
            })
        return sorted(result, key=lambda x: x["name"])

    def get_skill_content(self, name: str, license: Optional[License] = None) -> Optional[str]:
        """Get skill content if license allows access."""
        skill = self._skills.get(name)
        if not skill:
            return None
        if skill.tier == Tier.FREE:
            return skill.content
        if not license or not license.has_access(skill.tier):
            return None
        return skill.content

    def get_skill(self, name: str) -> Optional[SkillMetadata]:
        """Get skill metadata."""
        return self._skills.get(name)

    @property
    def total_skills(self) -> int:
        return len(self._skills)

    def skills_by_tier(self) -> dict[str, int]:
        """Count skills per tier."""
        counts: dict[str, int] = {}
        for skill in self._skills.values():
            counts[skill.tier.value] = counts.get(skill.tier.value, 0) + 1
        return counts
