"""
AI-LSC — Skill runtime resolver.

Scans the on-disk skill definition files under ``<base_dir>/skills/``
and extracts their ``SYSTEM`` blocks (the system prompt injected into
Ollama modelfiles).  This is pure string/regex work — no UI.
"""

from __future__ import annotations

import re
from pathlib import Path


class SkillRuntimeResolver:
    """Parses skill definitions to extract runtime system prompts.

    Each skill is a plain-text file whose ``SYSTEM`` block is either
    a triple-quoted string or a single-quoted string.  The resolver
    searches for these patterns and returns the first match.

    Parameters
    ----------
    skills_root :
        Absolute path to the directory containing skill definition files.
    """

    _PATTERNS: list[tuple[str, re.RegexFlag]] = [
        (r'SYSTEM\s+"""(.*?)"""', re.DOTALL | re.IGNORECASE),
        (r'SYSTEM\s+"(.*?)"', re.IGNORECASE),
    ]

    def __init__(self, skills_root: str | Path) -> None:
        self.skills_root = Path(skills_root)

    def extract_system_prompt(self, skill_name: str) -> str:
        """Return the SYSTEM block from *skill_name*, or ``""``."""
        path = self.skills_root / skill_name
        if not path.exists():
            return ""

        try:
            content = path.read_text(encoding="utf-8", errors="ignore")
        except OSError:
            return ""

        return next(
            (m.group(1).strip()
             for pattern, flags in self._PATTERNS
             for m in [re.search(pattern, content, flags)]
             if m),
            "",
        )

    def list_available_skills(self) -> list[str]:
        """Return sorted names of all files in the skills directory."""
        if not self.skills_root.is_dir():
            return []
        return sorted(
            p.name for p in self.skills_root.iterdir()
            if p.is_file()
        )
