"""Pipeline smoke tests. New layers/*/pipeline.py get a test automatically."""
import importlib
import json
from pathlib import Path

import pytest
import core.utils

_LAYERS_DIR = Path(__file__).resolve().parent.parent / "layers"


def _discover_layers():
    return sorted(
        p.parent.name
        for p in _LAYERS_DIR.glob("*/pipeline.py")
        if p.parent.name != "__pycache__"
    )


@pytest.mark.parametrize("layer_name", _discover_layers())
def test_pipeline_smoke(layer_name):
    mod = importlib.import_module(f"layers.{layer_name}.pipeline")
    assert callable(getattr(mod, "main", None)), f"{layer_name}.pipeline has no main()"

    mod.main()

    output_dir = core.utils.get_output_path("_probe.json").parent
    json_files = list(output_dir.glob("*.json"))
    assert json_files, f"{layer_name}: no JSON written to {output_dir}"

    for jf in json_files:
        assert jf.stat().st_size > 0, f"{jf.name} is empty"

        raw = jf.read_text()
        # literal NaN breaks json.loads — pipelines should guard against it
        assert "NaN" not in raw, f"{jf.name} has NaN values"

        try:
            data = json.loads(raw)
        except json.JSONDecodeError as exc:
            pytest.fail(f"{jf.name}: {exc}")

        assert len(data) > 0, f"{jf.name} is empty object/array"
