import json
from pathlib import Path

import pytest

import planemapper.provisioning.config as config_module

SAMPLE_CONFIG = {
    "home_lat": 51.5074,
    "home_lon": -0.1278,
    "coverage_radius_nm": 100,
    "wifi_ssid": "HomeNetwork",
    "wifi_password": "s3cr3t",
    "provisioned": False,
}


def test_read_raises_when_no_file_exists() -> None:
    with pytest.raises(FileNotFoundError):
        config_module.read()


def test_write_creates_file_with_correct_content(tmp_path: Path) -> None:
    config_module.write(SAMPLE_CONFIG)
    assert config_module.CONFIG_PATH.exists()
    with config_module.CONFIG_PATH.open() as f:
        data = json.load(f)
    for key in (
        "home_lat",
        "home_lon",
        "coverage_radius_nm",
        "wifi_ssid",
        "wifi_password",
        "provisioned",
    ):
        assert key in data
    assert data["home_lat"] == 51.5074
    assert data["wifi_ssid"] == "HomeNetwork"
    assert data["provisioned"] is False


def test_write_then_read_round_trips() -> None:
    config_module.write(SAMPLE_CONFIG)
    result = config_module.read()
    assert result == SAMPLE_CONFIG


def test_wipe_deletes_file() -> None:
    config_module.write(SAMPLE_CONFIG)
    assert config_module.CONFIG_PATH.exists()
    config_module.wipe()
    assert not config_module.CONFIG_PATH.exists()


def test_wipe_then_read_raises() -> None:
    config_module.write(SAMPLE_CONFIG)
    config_module.wipe()
    with pytest.raises(FileNotFoundError):
        config_module.read()


def test_wipe_is_idempotent() -> None:
    # wipe on a non-existent file should not raise
    config_module.wipe()
    config_module.wipe()


def test_config_path_is_in_tmp_path(tmp_path: Path) -> None:
    assert str(config_module.CONFIG_PATH).startswith(str(tmp_path))
