"""Verifier for mm-001: JSON to YAML Conversion."""

import json
from pathlib import Path

import pytest
import yaml


@pytest.fixture
def workspace(request):
    return Path(request.config.getoption("--workspace"))


@pytest.fixture
def source_json(workspace):
    path = workspace / "config.json"
    assert path.exists(), "config.json not found in workspace"
    with open(path) as f:
        return json.load(f)


@pytest.fixture
def output_yaml(workspace):
    path = workspace / "config.yaml"
    assert path.exists(), "config.yaml not found in workspace"
    return path.read_text()


@pytest.fixture
def parsed_yaml(output_yaml):
    return yaml.safe_load(output_yaml)


def test_output_file_exists(workspace):
    assert (workspace / "config.yaml").exists(), "config.yaml must exist"


def test_valid_yaml(output_yaml):
    """Output must be parseable YAML."""
    try:
        yaml.safe_load(output_yaml)
    except yaml.YAMLError as e:
        pytest.fail(f"config.yaml is not valid YAML: {e}")


def test_app_section(parsed_yaml, source_json):
    assert parsed_yaml["app"] == source_json["app"]


def test_server_section(parsed_yaml, source_json):
    assert parsed_yaml["server"] == source_json["server"]


def test_database_section(parsed_yaml, source_json):
    assert parsed_yaml["database"] == source_json["database"]


def test_logging_section(parsed_yaml, source_json):
    assert parsed_yaml["logging"] == source_json["logging"]


def test_features_section(parsed_yaml, source_json):
    assert parsed_yaml["features"] == source_json["features"]


def test_full_roundtrip(parsed_yaml, source_json):
    """The full parsed YAML must equal the original JSON data."""
    assert parsed_yaml == source_json


def test_null_preserved(parsed_yaml):
    """Null values must be preserved."""
    assert parsed_yaml["app"]["description"] is None


def test_boolean_preserved(parsed_yaml):
    """Boolean values must stay as booleans."""
    assert parsed_yaml["app"]["debug"] is False
    assert parsed_yaml["server"]["ssl"]["enabled"] is True


def test_nested_arrays(parsed_yaml):
    """Arrays of objects must be preserved."""
    handlers = parsed_yaml["logging"]["handlers"]
    assert len(handlers) == 3
    assert handlers[0]["type"] == "console"
    assert handlers[1]["type"] == "file"
    assert handlers[2]["type"] == "syslog"


def test_numeric_types(parsed_yaml):
    """Numeric values must remain numeric."""
    assert isinstance(parsed_yaml["server"]["port"], int)
    assert parsed_yaml["server"]["port"] == 8443
    assert isinstance(parsed_yaml["database"]["primary"]["pool"]["max_size"], int)
