"""Skill guidance generation for external agent CLIs."""

from __future__ import annotations

from pathlib import Path


_DATA_DIR = Path(__file__).parent / "data"


def _load_default_skill_text() -> str:
    return (_DATA_DIR / "WORAI_SKILL.md").read_text(encoding="utf-8")


def wordlift_md_path() -> Path:
    """Return the path to the static WORDLIFT.md context document."""
    return _DATA_DIR / "WORDLIFT.md"


def _discover_skill_templates(project_root: Path) -> list[Path]:
    skills_dir = project_root / "skills"
    if not skills_dir.exists() or not skills_dir.is_dir():
        return []
    skill_paths = [path for path in skills_dir.glob("*/SKILL.md") if path.is_file()]
    skill_paths.sort(key=lambda path: (path.parent.name != "worai-base", path.parent.name.lower()))
    return skill_paths


def build_skill_text(*, project_root: Path | None = None) -> str:
    """Return composed skill guidance from repo templates, or the builtin fallback."""
    root = (project_root or Path.cwd()).resolve()
    templates = _discover_skill_templates(root)
    if not templates:
        return _load_default_skill_text()
    blocks = [path.read_text(encoding="utf-8").strip() for path in templates]
    return "\n\n---\n\n".join(block for block in blocks if block)


def write_skill_file(directory: Path, *, project_root: Path | None = None) -> Path:
    """Write skill guidance into `directory` and return the file path."""
    directory.mkdir(parents=True, exist_ok=True)
    skill_path = directory / "WORAI_SKILL.md"
    skill_path.write_text(build_skill_text(project_root=project_root), encoding="utf-8")
    return skill_path
