from __future__ import annotations

import json
import os
import re
from pathlib import Path
from typing import Any, Iterable


SKILL_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
FRONTMATTER = re.compile(r"^---\s*\n[\s\S]*?\n---\s*\n", re.MULTILINE)


class RootSkillRegistry:
    """Load and select trusted Achon skills from the canonical root catalogue."""

    def __init__(self, root: str | Path | None = None):
        self.root = Path(root or os.getenv("ACHON_SKILLS_ROOT", "/skills")).resolve()
        self.registry_path = self.root / "registry.json"
        self._mtime_ns = -1
        self._payload: dict[str, Any] = {}
        self._entries: dict[str, dict[str, Any]] = {}

    def _refresh(self) -> None:
        stat = self.registry_path.stat()
        if stat.st_mtime_ns == self._mtime_ns:
            return
        payload = json.loads(self.registry_path.read_text(encoding="utf-8"))
        entries: dict[str, dict[str, Any]] = {}
        for raw in payload.get("skills") or []:
            skill_id = str(raw.get("id") or "")
            if not SKILL_ID.fullmatch(skill_id):
                raise ValueError(f"invalid skill id in root registry: {skill_id!r}")
            skill_file = (self.root / skill_id / "SKILL.md").resolve()
            if self.root not in skill_file.parents or not skill_file.is_file():
                raise ValueError(f"registered skill is missing SKILL.md: {skill_id}")
            entries[skill_id] = dict(raw)
        self._payload = payload
        self._entries = entries
        self._mtime_ns = stat.st_mtime_ns

    @property
    def version(self) -> int:
        self._refresh()
        return int(self._payload.get("version") or 0)

    def list(self, experience: str | None = None) -> list[dict[str, Any]]:
        self._refresh()
        values = list(self._entries.values())
        if experience:
            values = [item for item in values if experience in item.get("experiences", [])]
        return [dict(item) for item in values]

    def select(
        self,
        text: str,
        *,
        experience: str = "chat",
        explicit_ids: Iterable[str] = (),
        thorough: bool = False,
        feature: bool = False,
    ) -> list[str]:
        self._refresh()
        eligible = {
            skill_id: entry
            for skill_id, entry in self._entries.items()
            if experience in entry.get("experiences", [])
        }
        explicit = [
            skill_id
            for skill_id in explicit_ids
            if skill_id in eligible and SKILL_ID.fullmatch(skill_id)
        ]
        explicit.extend(
            skill_id
            for skill_id in eligible
            if f"${skill_id}" in text and skill_id not in explicit
        )
        selected: list[str] = []
        for skill_id, entry in eligible.items():
            if (
                experience in entry.get("always_for", [])
                or (feature and experience in entry.get("feature_for", []))
                or (thorough and experience in entry.get("thorough_for", []))
            ):
                selected.append(skill_id)
        scored: list[tuple[int, int, str]] = []
        for order, (skill_id, entry) in enumerate(eligible.items()):
            score = 1000 if skill_id in explicit else 0
            for pattern in entry.get("triggers", []):
                try:
                    if re.search(str(pattern), text, re.IGNORECASE):
                        score += 1
                except re.error:
                    continue
            if score:
                scored.append((score, -order, skill_id))
        scored.sort(reverse=True)
        limit = int(
            (self._payload.get("selection") or {})
            .get("max_specialized", {})
            .get(experience, 3)
        )
        specialized = [item[2] for item in scored[: max(limit, len(explicit))]]
        for skill_id in [*explicit, *specialized]:
            if skill_id not in selected:
                selected.append(skill_id)
        return selected

    def read(self, skill_id: str, *, max_characters: int = 5_000) -> str:
        self._refresh()
        if skill_id not in self._entries:
            return ""
        path = (self.root / skill_id / "SKILL.md").resolve()
        if self.root not in path.parents:
            return ""
        body = FRONTMATTER.sub("", path.read_text(encoding="utf-8"), count=1).strip()
        return body[:max_characters]

    def render(
        self,
        skill_ids: Iterable[str],
        *,
        max_each: int = 5_000,
        max_total: int = 16_000,
    ) -> str:
        sections: list[str] = []
        total = 0
        for skill_id in skill_ids:
            body = self.read(str(skill_id), max_characters=max_each)
            if not body:
                continue
            section = f"## Active Achon skill: {skill_id}\n{body}"
            remaining = max_total - total
            if remaining <= 0:
                break
            sections.append(section[:remaining])
            total += len(sections[-1])
        return "\n\n".join(sections)
