"""load_spec — TOML → ServiceSpec, incl. cloud_init_file + error paths."""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from mgf.cloud_provision import load_spec
from mgf.cloud_provision.exceptions import SpecError

if TYPE_CHECKING:
    from pathlib import Path

_VALID = 'name = "svc"\nflavor = "a2-ram4-disk40"\nimage = "Ubuntu 24.04 LTS"\n'


def test_load_valid(tmp_path: Path) -> None:
    f = tmp_path / "svc.toml"
    f.write_text(_VALID)
    spec = load_spec(f)
    assert spec.name == "svc"
    assert spec.network == "ext-net1"  # default applied


def test_cloud_init_file_is_inlined(tmp_path: Path) -> None:
    (tmp_path / "init.yml").write_text("#cloud-config\npackages: [python3-venv]\n")
    f = tmp_path / "svc.toml"
    f.write_text(_VALID + 'cloud_init_file = "init.yml"\n')
    spec = load_spec(f)
    assert spec.cloud_init is not None
    assert "python3-venv" in spec.cloud_init


def test_missing_spec_file(tmp_path: Path) -> None:
    with pytest.raises(SpecError, match="not found"):
        load_spec(tmp_path / "nope.toml")


def test_invalid_toml(tmp_path: Path) -> None:
    f = tmp_path / "bad.toml"
    f.write_text("name = = =\n")
    with pytest.raises(SpecError, match="invalid TOML"):
        load_spec(f)


def test_missing_cloud_init_file(tmp_path: Path) -> None:
    f = tmp_path / "svc.toml"
    f.write_text(_VALID + 'cloud_init_file = "absent.yml"\n')
    with pytest.raises(SpecError, match="cloud_init_file not found"):
        load_spec(f)


def test_unknown_field_rejected(tmp_path: Path) -> None:
    f = tmp_path / "svc.toml"
    f.write_text(_VALID + 'bogus = "x"\n')
    with pytest.raises(SpecError, match="invalid ServiceSpec"):
        load_spec(f)
