import json
from pathlib import Path

from armorer.config import ConfigManager
from armorer.core import ArmorerCoreHandler
from armorer.registry import AppRegistry


def _setup(tmp_path: Path, monkeypatch):
    config_dir = tmp_path / "armorer"
    config_dir.mkdir(parents=True, exist_ok=True)
    monkeypatch.setattr(AppRegistry, "REGISTRY_FILE", config_dir / "registry.json")
    monkeypatch.setattr(ConfigManager, "VAULT_FILE", config_dir / "vault.json")
    monkeypatch.setattr(ConfigManager, "CONFIG_DIR", config_dir)
    (config_dir / "vault.json").write_text(json.dumps({"keys": {}, "secrets": {}}, indent=2))
    return config_dir


def test_remote_unsigned_task_rejected_when_no_signing_key(tmp_path: Path, monkeypatch):
    config_dir = _setup(tmp_path, monkeypatch)
    handler = ArmorerCoreHandler(config_dir=config_dir)
    inbox = config_dir / "inbox"
    task_path = inbox / "t1.json"
    task_path.write_text(
        json.dumps(
            {
                "id": "t1",
                "prompt": "status",
                "source": "telegram",
                "timestamp": 0,
                "metadata": {"channel_id": "1", "user_id": "1"},
            }
        )
    )
    handler._process_inbox_task(str(task_path))
    out = json.loads((config_dir / "outbox" / "t1.json").read_text())
    payload = json.loads(out["response"])
    assert "signature verification failed" in payload.get("message", "").lower()


def test_local_unsigned_cli_task_allowed_by_default(tmp_path: Path, monkeypatch):
    config_dir = _setup(tmp_path, monkeypatch)
    handler = ArmorerCoreHandler(config_dir=config_dir)

    from armorer import core as core_mod

    def _noop_init_agent(self, *args, **kwargs):
        return None

    def _fake_run(self, *args, **kwargs):
        return {"message": "ok"}

    monkeypatch.setattr(core_mod.BaseAgent, "init_agent", _noop_init_agent, raising=True)
    monkeypatch.setattr(core_mod.BaseAgent, "run", _fake_run, raising=True)

    inbox = config_dir / "inbox"
    task_path = inbox / "t2.json"
    task_path.write_text(
        json.dumps(
            {
                "id": "t2",
                "prompt": "status",
                "source": "cli",
                "timestamp": 0,
                "metadata": {"channel_id": "1", "user_id": "1"},
            }
        )
    )
    handler._process_inbox_task(str(task_path))
    out = json.loads((config_dir / "outbox" / "t2.json").read_text())
    payload = json.loads(out["response"])
    assert payload.get("message") == "ok"
