import sys
from io import StringIO
from pathlib import Path

from l4d2host.instances import initialize_instance


def test_initialize_writes_files(tmp_path: Path) -> None:
    spec = tmp_path / "spec.yaml"
    spec.write_text("port: 27015\noverlays: [a,b]\nconfig: ['sv_consistency 1']\n")

    initialize_instance("alpha", spec, root=tmp_path)

    assert (tmp_path / "instances/alpha/instance.env").exists()
    assert (tmp_path / "instances/alpha/server.cfg").exists()


def test_empty_config_writes_empty_server_cfg(tmp_path: Path) -> None:
    spec = tmp_path / "spec.yaml"
    spec.write_text("port: 27015\n")

    initialize_instance("alpha", spec, root=tmp_path)

    assert (tmp_path / "instances/alpha/server.cfg").read_text() == ""


def test_initialize_uses_configured_left4me_root(tmp_path: Path, monkeypatch) -> None:
    monkeypatch.setenv("LEFT4ME_ROOT", str(tmp_path))
    spec = tmp_path / "spec.yaml"
    spec.write_text("port: 27015\noverlays: [standard]\n")

    initialize_instance("alpha", spec)

    env = (tmp_path / "instances/alpha/instance.env").read_text()
    assert f"L4D2_LOWERDIRS={tmp_path}/overlays/standard:{tmp_path}/installation" in env


def test_initialize_instance_emits_steps(tmp_path: Path) -> None:
    spec = tmp_path / "spec.yaml"
    spec.write_text("port: 27015\noverlays: [standard]\n")

    steps: list[str] = []
    initialize_instance("alpha", spec, root=tmp_path, on_stdout=steps.append)

    assert steps == [
        "Step: creating instance directories...",
        "Step: writing instance.env...",
        "Step: writing server.cfg...",
        "Step: persisting spec...",
        "Step: initialization complete.",
    ]


def test_initialize_persists_spec_to_instance_dir(tmp_path: Path) -> None:
    spec = tmp_path / "spec.yaml"
    spec.write_text(
        "port: 27015\n"
        "overlays:\n"
        "  - {path: '5', alias: overlay_5}\n"
        "  - path: '6'\n"
    )

    initialize_instance("alpha", spec, root=tmp_path)

    persisted = tmp_path / "instances" / "alpha" / "spec.yaml"
    assert persisted.exists()
    assert "overlay_5" in persisted.read_text()
