import json
import os
import stat

from sitedrop.client.config import ClientConfig


def test_default_config():
    config = ClientConfig()
    assert config.server_url == ""
    assert config.token == ""
    assert config.password == ""


def test_save_and_load(tmp_path):
    path = tmp_path / ".sitedroprc"
    config = ClientConfig(
        server_url="http://localhost:8000", token="tok", password="pw"
    )
    config.save(path)

    loaded = ClientConfig.load(path)
    assert loaded.server_url == "http://localhost:8000"
    assert loaded.token == "tok"
    assert loaded.password == "pw"


def test_save_sets_permissions(tmp_path):
    path = tmp_path / ".sitedroprc"
    config = ClientConfig(server_url="http://localhost:8000")
    config.save(path)

    mode = stat.S_IMODE(os.stat(path).st_mode)
    assert mode == 0o600


def test_load_nonexistent_returns_default(tmp_path):
    path = tmp_path / "nope"
    config = ClientConfig.load(path)
    assert config.server_url == ""


def test_load_ignores_unknown_fields(tmp_path):
    path = tmp_path / ".sitedroprc"
    path.write_text(json.dumps({"server_url": "http://x", "extra": "ignored"}))
    loaded = ClientConfig.load(path)
    assert loaded.server_url == "http://x"


def test_save_overwrites(tmp_path):
    path = tmp_path / ".sitedroprc"
    ClientConfig(token="a").save(path)
    ClientConfig(token="b").save(path)
    assert ClientConfig.load(path).token == "b"


def test_load_corrupted_json(tmp_path):
    path = tmp_path / ".sitedroprc"
    path.write_text("not json!!")
    config = ClientConfig.load(path)
    assert config.server_url == ""
    assert config.token == ""
    assert config.password == ""


def test_env_var_override(tmp_path, monkeypatch):
    custom_path = tmp_path / "custom_rc"
    monkeypatch.setenv("SITEDROP_CLIENT_CONFIG", str(custom_path))
    import importlib
    import sitedrop.client.config as cfg

    importlib.reload(cfg)
    assert cfg.DEFAULT_CLIENT_CONFIG == custom_path
    monkeypatch.delenv("SITEDROP_CLIENT_CONFIG", raising=False)
    importlib.reload(cfg)
