from pathlib import Path

import pytest

from session_hub_core.sync import (
    load_host_state,
    resolve_hostname,
    save_host_state,
    validate_hostname,
)


def test_resolve_hostname_no_state_file(tmp_path: Path) -> None:
    hostname = resolve_hostname(state_file=tmp_path / "host.json", detected="myhost")
    assert hostname == "myhost"


def test_resolve_hostname_match(tmp_path: Path) -> None:
    state_file = tmp_path / "host.json"
    save_host_state("myhost", state_file=state_file)
    hostname = resolve_hostname(state_file=state_file, detected="myhost")
    assert hostname == "myhost"


def test_resolve_hostname_mismatch_uses_previous(tmp_path: Path) -> None:
    state_file = tmp_path / "host.json"
    save_host_state("oldhost", state_file=state_file)
    hostname = resolve_hostname(state_file=state_file, detected="renamed-host")
    assert hostname == "oldhost"


def test_resolve_hostname_override_wins(tmp_path: Path) -> None:
    state_file = tmp_path / "host.json"
    save_host_state("oldhost", state_file=state_file)
    hostname = resolve_hostname(override="custom", state_file=state_file, detected="renamed-host")
    assert hostname == "custom"


def test_validate_hostname_rejects_invalid() -> None:
    with pytest.raises(ValueError):
        validate_hostname("")
    with pytest.raises(ValueError):
        validate_hostname("a" * 101)
    with pytest.raises(ValueError):
        validate_hostname("a\nb")


def test_save_and_load_state(tmp_path: Path) -> None:
    state_file = tmp_path / "host.json"
    save_host_state("myhost", state_file=state_file)
    state = load_host_state(state_file=state_file)
    assert state is not None
    assert state.hostname == "myhost"
    assert state.last_synced_at is not None


def test_load_missing_state_file(tmp_path: Path) -> None:
    assert load_host_state(state_file=tmp_path / "nope.json") is None


def test_load_corrupt_state_file(tmp_path: Path) -> None:
    state_file = tmp_path / "host.json"
    state_file.write_text("{not json")
    assert load_host_state(state_file=state_file) is None
