from __future__ import annotations

from beaver.skills.authoring.format import (
    CANONICAL_SKILL_SECTION_HEADINGS,
    canonical_skill_format_instructions,
    canonicalize_skill_body,
    is_canonical_skill_body,
    parse_skill_rewrite_json,
)


def test_canonical_skill_body_contains_required_sections() -> None:
    body = canonicalize_skill_body(
        title="Filesystem Operation",
        overview="Read and update project files safely.",
        tools=["read_file", "write_file"],
        workflow=["Inspect the file before editing.", "Use the smallest safe edit."],
        validation=["Re-read changed files before reporting completion."],
        boundaries=["Do not edit files outside the workspace."],
        anti_patterns=["Do not overwrite files without reading them first."],
    )

    assert is_canonical_skill_body(body)
    for heading in CANONICAL_SKILL_SECTION_HEADINGS:
        assert heading in body


def test_canonical_skill_format_instructions_are_prompt_ready() -> None:
    instructions = canonical_skill_format_instructions()

    assert "Canonical Beaver SKILL.md format" in instructions
    assert "frontmatter" in instructions
    assert "name" in instructions
    assert "description" in instructions
    assert "tools" in instructions
    for heading in CANONICAL_SKILL_SECTION_HEADINGS:
        assert heading in instructions


def test_parse_skill_rewrite_json_backfills_frontmatter_tools_from_required_tools_section() -> None:
    payload = parse_skill_rewrite_json(
        """{
          "frontmatter": {
            "name": "weather-search",
            "description": "weather lookup",
            "tools": []
          },
          "content": "# Weather Search\\n\\n## Overview\\n\\nLook up weather.\\n\\n## When to Use\\n\\n- Weather requests.\\n\\n## Required Tools\\n\\n- `web_fetch`\\n- `web_search`\\n\\n## Workflow\\n\\n- Fetch current weather.\\n\\n## Validation\\n\\n- Check source freshness.\\n\\n## Boundaries\\n\\n- Do not guess.\\n\\n## Anti-Patterns\\n\\n- Do not fabricate data.\\n"
        }""",
        skill_name="weather-search",
    )

    assert payload is not None
    assert payload["frontmatter"]["tools"] == ["web_fetch", "web_search"]
