from unittest.mock import patch

from armorer.skills import Skill, SkillManager


def test_required_env_vars_extracts_placeholders(tmp_path, monkeypatch):
    monkeypatch.setattr(SkillManager, "SKILLS_FILE", tmp_path / "skills.json")
    manager = SkillManager()
    skill = Skill(
        name="test-skill",
        description="test",
        config={"command": "npx", "env": {"BRAVE_API_KEY": "${BRAVE_API_KEY}", "OTHER": "static"}},
    )

    assert manager.required_env_vars(skill) == ["BRAVE_API_KEY"]


@patch("armorer.skills.shutil.which", return_value="/usr/bin/npx")
@patch("armorer.skills.subprocess.run")
def test_ensure_skill_ready_validates_npx_package(mock_run, mock_which, tmp_path, monkeypatch):
    monkeypatch.setattr(SkillManager, "SKILLS_FILE", tmp_path / "skills.json")
    manager = SkillManager()
    mock_run.return_value.returncode = 0
    mock_run.return_value.stdout = ""
    mock_run.return_value.stderr = ""
    manager.add_skill(
        Skill(
            name="demo",
            description="demo",
            config={"command": "npx", "args": ["-y", "@scope/demo-server"], "env": {"TOKEN": "${TOKEN}"}},
        )
    )

    result = manager.ensure_skill_ready("demo", env_lookup=lambda key: "value" if key == "TOKEN" else None)

    assert result.ready is True
    mock_run.assert_called_once()
    assert mock_run.call_args[0][0] == ["npx", "-y", "@scope/demo-server", "--help"]


@patch("armorer.skills.shutil.which", return_value="/usr/bin/npx")
def test_check_skill_reports_missing_env(mock_which, tmp_path, monkeypatch):
    monkeypatch.setattr(SkillManager, "SKILLS_FILE", tmp_path / "skills.json")
    manager = SkillManager()
    manager.add_skill(
        Skill(
            name="needs-key",
            description="demo",
            config={"command": "npx", "args": ["-y", "@scope/demo-server"], "env": {"BRAVE_API_KEY": "${BRAVE_API_KEY}"}},
        )
    )

    result = manager.check_skill("needs-key", env_lookup=lambda key: None)

    assert result.ready is False
    assert result.missing_env == ["BRAVE_API_KEY"]
