from pathlib import Path

from armorer.registry import AppRegistry
from armorer.tools.interaction import redact_secret, update_app_metadata


def _configure_registry(tmp_path: Path, monkeypatch) -> None:
    monkeypatch.chdir(tmp_path)
    monkeypatch.setattr(AppRegistry, "REGISTRY_FILE", tmp_path / ".armorer" / "registry.json")


def _seed_openclaw_runtime(tmp_path: Path) -> Path:
    install_dir = tmp_path / "installed" / "openclaw"
    install_dir.mkdir(parents=True)
    (install_dir / "docker-compose.yml").write_text(
        "services:\n"
        "  openclaw-cli:\n"
        "    image: ghcr.io/openclaw/openclaw:main\n"
    )
    return install_dir


def test_update_app_metadata_uses_openclaw_fallback_when_registry_missing(tmp_path: Path, monkeypatch):
    _configure_registry(tmp_path, monkeypatch)
    install_dir = _seed_openclaw_runtime(tmp_path)

    result = update_app_metadata("openclaw", "monitor_targets", ["sessions/**/*.json"])

    assert result == "Successfully updated 'monitor_targets' for openclaw."
    app = AppRegistry().get_app("openclaw")
    assert app is not None
    assert app.install_path == str(install_dir)
    assert "sessions/**/*.json" in app.monitor_targets


def test_redact_secret_uses_openclaw_fallback_when_registry_missing(tmp_path: Path, monkeypatch):
    _configure_registry(tmp_path, monkeypatch)
    _seed_openclaw_runtime(tmp_path)
    secret_file = tmp_path / "installed" / "openclaw" / "secrets.txt"
    secret_file.write_text("OPENAI_API_KEY=sk-test-123\n")

    result = redact_secret("openclaw", "sk-test-123", target_files=["secrets.txt"])

    assert "Successfully masked 1 files in openclaw." in result
    assert "[REDACTED]" in secret_file.read_text()
