import stat

from a2a_agent.config import AgentConfig
from a2a_agent.config import BrokerConfig
from a2a_agent.config import DEFAULT_BROKER_HOST
from a2a_agent.config import DEFAULT_BROKER_PORT
from a2a_agent.config import DEFAULT_EXECUTOR
from a2a_agent.config import DEFAULT_ROOM
from a2a_agent.config import DeviceRole
from a2a_agent.config import PendingPairing
from a2a_agent.config import load_config
from a2a_agent.config import save_config


def test_default_config_values(tmp_path) -> None:
    config = load_config(tmp_path / "missing.yaml")

    assert config.room == DEFAULT_ROOM
    assert config.device_name
    assert config.broker == BrokerConfig(host=DEFAULT_BROKER_HOST, port=DEFAULT_BROKER_PORT)
    assert config.role == "worker"
    assert config.token is None
    assert config.devices == {}
    assert config.aliases == {}
    assert config.pending_pairings == {}
    assert config.executor == DEFAULT_EXECUTOR


def test_save_load_round_trip_and_file_mode(tmp_path) -> None:
    path = tmp_path / "config.yaml"
    config = AgentConfig(
        room="team",
        device_name="commander",
        broker=BrokerConfig(host="broker.example.com", port=8883, tls=True),
        role="commander",
        devices={
            "device-b": DeviceRole(
                role="research",
                description="collect local context",
            )
        },
        aliases={
            "회사 PC": "device-b",
        },
        pending_pairings={
            "ABC234": PendingPairing(
                device_name="device-b",
                room="team",
                expires_at="2026-07-08T00:10:00Z",
            )
        },
        executor="opencode",
    )

    saved_path = save_config(config, path)
    loaded = load_config(path)

    assert saved_path == path
    assert loaded == config
    assert stat.S_IMODE(path.stat().st_mode) == 0o600


def test_worker_token_is_saved(tmp_path) -> None:
    path = tmp_path / "config.yaml"
    config = AgentConfig(
        room="team",
        device_name="device-b",
        broker=BrokerConfig(host="broker.example.com", port=1883, tls=False),
        role="worker",
        token="runtime-generated-token",
    )

    save_config(config, path)

    assert load_config(path) == config
