import json
import pytest
from pathlib import Path
from unittest.mock import patch

from notilens.config import save_agent, get_agent_config, remove_agent, list_agents, read_config


@pytest.fixture(autouse=True)
def tmp_config(tmp_path, monkeypatch):
    config_file = tmp_path / ".notilens_config.json"
    monkeypatch.setattr("notilens.config.CONFIG_FILE", config_file)
    yield config_file


def test_save_and_get_agent():
    save_agent("my-agent", "tok123", "sec456")
    conf = get_agent_config("my-agent")
    assert conf["token"] == "tok123"
    assert conf["secret"] == "sec456"


def test_get_agent_missing_returns_none():
    assert get_agent_config("nonexistent") is None


def test_remove_agent():
    save_agent("my-agent", "tok", "sec")
    assert remove_agent("my-agent") is True
    assert get_agent_config("my-agent") is None


def test_remove_agent_missing_returns_false():
    assert remove_agent("ghost") is False


def test_list_agents():
    save_agent("agent-a", "t1", "s1")
    save_agent("agent-b", "t2", "s2")
    agents = list_agents()
    assert "agent-a" in agents
    assert "agent-b" in agents


def test_multiple_agents_isolated():
    save_agent("a", "ta", "sa")
    save_agent("b", "tb", "sb")
    assert get_agent_config("a")["token"] == "ta"
    assert get_agent_config("b")["token"] == "tb"


def test_save_agent_overwrites():
    save_agent("my-agent", "old-tok", "old-sec")
    save_agent("my-agent", "new-tok", "new-sec")
    conf = get_agent_config("my-agent")
    assert conf["token"] == "new-tok"
    assert conf["secret"] == "new-sec"


def test_config_file_format(tmp_config):
    save_agent("my-agent", "tok", "sec")
    data = json.loads(tmp_config.read_text())
    assert "my-agent" in data
    assert data["my-agent"] == {"token": "tok", "secret": "sec"}
