from pathlib import Path

from typer.testing import CliRunner

from armorer.main import app


runner = CliRunner()


def test_skill_install_user_scope_all_targets(monkeypatch, tmp_path):
    monkeypatch.setenv("HOME", str(tmp_path))

    result = runner.invoke(app, ["skill", "install", "--target", "all"])

    assert result.exit_code == 0
    assert (tmp_path / ".codex" / "skills" / "armorer" / "SKILL.md").exists()
    assert (tmp_path / ".claude" / "skills" / "armorer" / "SKILL.md").exists()
    assert (tmp_path / ".codex" / "skills" / "armorer" / "agents" / "openai.yaml").exists()


def test_skill_install_project_scope(monkeypatch, tmp_path):
    monkeypatch.chdir(tmp_path)

    result = runner.invoke(app, ["skill", "install", "--target", "claude", "--scope", "project"])

    assert result.exit_code == 0
    assert (tmp_path / ".claude" / "skills" / "armorer" / "SKILL.md").exists()
    assert "project" in result.stdout.lower()


def test_skill_install_refuses_to_overwrite_without_force(monkeypatch, tmp_path):
    monkeypatch.setenv("HOME", str(tmp_path))
    existing = tmp_path / ".codex" / "skills" / "armorer"
    existing.mkdir(parents=True)
    (existing / "SKILL.md").write_text("old skill", encoding="utf-8")

    result = runner.invoke(app, ["skill", "install", "--target", "codex"])

    assert result.exit_code != 0
    assert "already exists" in result.output
    assert (existing / "SKILL.md").read_text(encoding="utf-8") == "old skill"


def test_skill_install_force_replaces_existing_destination(monkeypatch, tmp_path):
    monkeypatch.setenv("HOME", str(tmp_path))
    existing = tmp_path / ".codex" / "skills" / "armorer"
    existing.mkdir(parents=True)
    (existing / "SKILL.md").write_text("old skill", encoding="utf-8")

    result = runner.invoke(app, ["skill", "install", "--target", "codex", "--force"])

    assert result.exit_code == 0
    assert "Installed skill 'armorer'" in result.stdout
    assert "old skill" not in (existing / "SKILL.md").read_text(encoding="utf-8")
