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

from __future__ import annotations

from pathlib import Path


_DEFAULT_SKILL_TEXT = """# worai MCP Skill

Use MCP tools directly. Prefer typed tools over fallback command execution.

## Tools
- `worai_version`: show installed worai version.
- `worai_help`: show help for root or subcommand path.
- `worai_graph_validate`: validate RDF files/URLs with SHACL.
- `worai_graph_export`: export graph data (optional validation).
- `worai_graph_sync_run_start`: start graph sync as an async job.
- `worai_structured_data_validate_page`: validate JSON-LD extracted from a webpage.
- `worai_structured_data_inventory_start`: start structured-data inventory as an async job.
- `worai_web_pages_classify_types`: classify pages into schema.org types.
- `worai_job_status`: check async job status.
- `worai_job_output`: read incremental async job logs/output.
- `worai_job_events`: read structured async progress events (cursor-based).
- `worai_job_cancel`: cancel async jobs.
- `worai_cli_exec`: fallback executor for commands not covered above.

## Configuration resolution
- Per-call `config_path` / `profile` overrides are highest precedence.
- Otherwise session defaults from `worai agent` are used.
- If neither is set, worai uses normal env/discovery (`WORAI_CONFIG`, nearest `worai.toml`, etc.).

## Usage policy
1. Prefer typed tools first.
2. Use `worai_help` before unfamiliar operations.
3. Use `worai_cli_exec` only when no typed tool matches.
4. For `*_start` tools, poll with `worai_job_status` and `worai_job_events`; use `worai_job_output` for log details.
5. Include explicit `profile` for profile-specific tasks.
"""


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 _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
