from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import pytest


ROOT = Path(__file__).resolve().parents[1]
EXAMPLE_SMOKE_PATHS = [
    "examples/public_api_surface_examples.py",
    "examples/analytics_spreads_examples.py",
    "examples/analytics_yields_examples.py",
    "examples/bonds_examples.py",
    "examples/bonds_callable_examples.py",
    "examples/curves_examples.py",
    "examples/curves_calibration_examples.py",
    "examples/data_provider_surface_examples.py",
    "examples/io_file_and_storage_examples.py",
    "examples/engine_portfolio_examples.py",
    "examples/engine_reactive_examples.py",
    "examples/portfolio_benchmark_examples.py",
    "examples/portfolio_etf_surface_examples.py",
    "examples/portfolio_summary_examples.py",
    "examples/end_to_end_platform_examples.py",
]


@pytest.mark.parametrize("example_path", EXAMPLE_SMOKE_PATHS)
def test_example_script_smoke(example_path: str) -> None:
    env = os.environ.copy()
    env["PYTHONPATH"] = str(ROOT / "src")
    completed = subprocess.run(
        [sys.executable, example_path],
        cwd=ROOT,
        env=env,
        capture_output=True,
        text=True,
        timeout=60,
        check=False,
    )

    assert completed.returncode == 0, (
        f"{example_path} failed with exit code {completed.returncode}\n"
        f"stdout:\n{completed.stdout}\n"
        f"stderr:\n{completed.stderr}"
    )


def test_examples_do_not_import_removed_top_level_spreads_namespace() -> None:
    for path in sorted((ROOT / "examples").glob("*.py")):
        text = path.read_text(encoding="utf-8")
        assert "fuggers_py.spreads" not in text, f"{path} still imports the removed top-level spreads namespace"
