"""Tests for lazy skill discovery and loading."""

from pathlib import Path

import pytest

from yier_agents.src.skill import SkillCatalog, parse_skill_document
from yier_agents.src.tools.skill_load import SkillLoadTool
from yier_agents.src.tool import ToolContext


def test_parse_skill_document(tmp_path):
    """Test parsing one valid SKILL.md document."""
    skill_dir = tmp_path / ".agents" / "skills" / "demo-skill"
    skill_dir.mkdir(parents=True)
    skill_file = skill_dir / "SKILL.md"
    skill_file.write_text(
        "\n".join(
            [
                "---",
                "name: demo-skill",
                "description: Demo skill for testing.",
                "---",
                "",
                "# Demo Skill",
                "",
                "Use this for demos.",
            ]
        ),
        encoding="utf-8",
    )

    document = parse_skill_document(skill_file)

    assert document is not None
    assert document.name == "demo-skill"
    assert document.description == "Demo skill for testing."
    assert "# Demo Skill" in document.content


def test_skill_catalog_discovers_project_skills(tmp_path):
    """Test discovery from project-local .agents and .claude skill directories."""
    project_dir = tmp_path / "project"
    project_dir.mkdir()
    (project_dir / ".git").mkdir()

    agents_skill_dir = project_dir / ".agents" / "skills" / "agent-skill"
    agents_skill_dir.mkdir(parents=True)
    (agents_skill_dir / "SKILL.md").write_text(
        "\n".join(
            [
                "---",
                "name: agent-skill",
                "description: Agent scoped skill.",
                "---",
                "",
                "Agent instructions.",
            ]
        ),
        encoding="utf-8",
    )

    claude_skill_dir = project_dir / ".claude" / "skills" / "claude-skill"
    claude_skill_dir.mkdir(parents=True)
    (claude_skill_dir / "SKILL.md").write_text(
        "\n".join(
            [
                "---",
                "name: claude-skill",
                "description: Claude scoped skill.",
                "---",
                "",
                "Claude instructions.",
            ]
        ),
        encoding="utf-8",
    )

    catalog = SkillCatalog.discover(project_dir, include_project=True, include_global=False)

    assert [skill.name for skill in catalog.list()] == ["agent-skill", "claude-skill"]
    assert agents_skill_dir in catalog.dirs()
    assert claude_skill_dir in catalog.dirs()


@pytest.mark.asyncio
async def test_skill_load_tool_returns_skill_block(tmp_path):
    """Test the lazy skill tool returns content, base dir, and sampled files."""
    skill_dir = tmp_path / ".agents" / "skills" / "tool-skill"
    (skill_dir / "scripts").mkdir(parents=True)
    (skill_dir / "references").mkdir(parents=True)
    (skill_dir / "SKILL.md").write_text(
        "\n".join(
            [
                "---",
                "name: tool-skill",
                "description: Tool test skill.",
                "---",
                "",
                "# Tool Skill",
                "",
                "Read scripts/demo.py before running it.",
            ]
        ),
        encoding="utf-8",
    )
    (skill_dir / "scripts" / "demo.py").write_text("print('demo')\n", encoding="utf-8")
    (skill_dir / "references" / "guide.md").write_text("guide\n", encoding="utf-8")

    catalog = SkillCatalog.discover(tmp_path, include_project=False, extra_paths=[tmp_path / ".agents" / "skills"])
    tool = SkillLoadTool(catalog)
    ctx = ToolContext(session_id="s1", message_id="m1", call_id="c1")

    result = await tool.execute(tool.parameters(name="tool-skill"), ctx)

    assert '<skill_content name="tool-skill">' in result.content
    assert f"Base directory for this skill: {skill_dir.resolve().as_uri()}" in result.content
    assert "<file>" in result.content
    assert "scripts/demo.py" in result.content
