from __future__ import annotations

from pathlib import Path

from openclaw_lite.skills import SkillManager, create_skill
from openclaw_lite.skills.loader import load_skill
from openclaw_lite.skills.runtime import SkillRegistry


def test_create_skill_with_extra_bundle_files(tmp_path: Path) -> None:
    skill_dir = create_skill(
        tmp_path,
        name="bundle-skill",
        description="Skill with resources",
        extra_files={
            "resources/rules.txt": "always be careful",
            "examples/demo.json": '{"ok": true}',
        },
    )

    assert (skill_dir / "resources" / "rules.txt").read_text(encoding="utf-8") == "always be careful"
    assert (skill_dir / "examples" / "demo.json").exists()

    loaded = load_skill(skill_dir)
    assert sorted(loaded.manifest.metadata.get("bundle_files", [])) == [
        "examples/demo.json",
        "resources/rules.txt",
    ]


def test_skill_manager_updates_extra_files_and_reload_detects_change(tmp_path: Path) -> None:
    manager = SkillManager({"skills_root": str(tmp_path)})
    created = manager.create_skill(
        name="upgrade-me",
        description="Upgradeable skill",
        extra_files={"resources/state.txt": "v1"},
    )
    assert created["extra_files"] == ["resources/state.txt"]

    registry = SkillRegistry(tmp_path)
    summary = registry.reload()
    assert summary.loaded == ["upgrade-me"]

    updated = manager.update_skill(
        name="upgrade-me",
        extra_files={
            "resources/state.txt": "v2",
            "scripts/helper.py": "print('ok')\n",
        },
    )
    assert sorted(updated["extra_files"]) == ["resources/state.txt", "scripts/helper.py"]

    second = registry.reload()
    assert second.reloaded == ["upgrade-me"]
    assert (tmp_path / "upgrade-me" / "scripts" / "helper.py").exists()


def test_list_skills_exposes_bundle_files(tmp_path: Path) -> None:
    manager = SkillManager({"skills_root": str(tmp_path)})
    manager.create_skill(
        name="listed-skill",
        description="Listed skill",
        extra_files={"resources/readme.txt": "hello"},
    )
    skills = manager.list_skills()
    assert skills[0]["bundle_files"] == ["resources/readme.txt"]
