from pathlib import Path

import pytest

from l4d2host.spec import OverlayRef, load_spec


def test_minimal_spec_parses_string_shorthand(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text("port: 27015\noverlays: [standard]\n")
    spec = load_spec(path)
    assert spec.port == 27015
    assert spec.overlays == [OverlayRef(path="standard")]


def test_overlay_dict_with_alias(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text(
        "port: 27015\n"
        "overlays:\n"
        "  - {path: '6', alias: overlay_6}\n"
        "  - path: '7'\n"
    )
    spec = load_spec(path)
    assert spec.overlays == [
        OverlayRef(path="6", alias="overlay_6"),
        OverlayRef(path="7", alias=None),
    ]


def test_defaults_are_empty_lists(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text("port: 27015\n")
    spec = load_spec(path)
    assert spec.overlays == []
    assert spec.arguments == []
    assert spec.config == []


def test_missing_port_fails(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text("overlays: [standard]\n")
    with pytest.raises((KeyError, ValueError, TypeError)):
        load_spec(path)


def test_unknown_keys_ignored(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text("port: 27015\nfoo: bar\n")
    spec = load_spec(path)
    assert spec.port == 27015


def test_overlay_dict_missing_path_rejected(tmp_path: Path) -> None:
    path = tmp_path / "server.yaml"
    path.write_text("port: 27015\noverlays:\n  - {alias: overlay_6}\n")
    with pytest.raises(ValueError):
        load_spec(path)
