"""Tests that verify all reference examples run without errors."""

from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

EXAMPLES_DIR = Path(__file__).parent.parent / "examples"


def _run_example(name: str) -> None:
    """Import and execute an example script as a module."""
    path = EXAMPLES_DIR / name
    spec = importlib.util.spec_from_file_location(f"example_{name}", path)
    assert spec is not None, f"Could not load {path}"
    assert spec.loader is not None
    mod = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = mod
    spec.loader.exec_module(mod)
    del sys.modules[spec.name]


class TestExamples:
    def test_quickstart(self):
        _run_example("quickstart.py")

    def test_causal_discovery(self):
        _run_example("causal_discovery.py")

    def test_scenario_simulation(self):
        _run_example("scenario_simulation.py")

    def test_fair_lending(self):
        _run_example("fair_lending.py")

    def test_data_quality(self):
        _run_example("data_quality.py")

    def test_cecl_pipeline(self):
        _run_example("cecl_pipeline.py")

    def test_ccar_stress_test(self):
        _run_example("ccar_stress_test.py")

    def test_fair_lending_audit(self):
        _run_example("fair_lending_audit.py")

    def test_all_examples_exist(self):
        expected = [
            "quickstart.py",
            "causal_discovery.py",
            "scenario_simulation.py",
            "fair_lending.py",
            "data_quality.py",
            "cecl_pipeline.py",
            "ccar_stress_test.py",
            "fair_lending_audit.py",
        ]
        for name in expected:
            assert (EXAMPLES_DIR / name).exists(), f"Missing example: {name}"
