from __future__ import annotations

import importlib.util
import os
import subprocess
import sys

import pytest

_MISSING_ENVS = any(importlib.util.find_spec(m) is None for m in ("gymnasium", "minigrid"))


@pytest.mark.skipif(_MISSING_ENVS, reason="gymnasium/minigrid not available")
def test_minigrid_learning_curves_smoke(tmp_path) -> None:
    # Run a tiny learning-curve job if env extras are available.
    out_dir = tmp_path / "curves"
    plot_dir = tmp_path / "plots"
    out_dir.mkdir(parents=True, exist_ok=True)
    plot_dir.mkdir(parents=True, exist_ok=True)
    # Prefer MemoryS17; fall back to a tiny, ubiquitous empty env if unavailable
    import gymnasium as gym  # type: ignore

    try:
        env_id = "MiniGrid-MemoryS17-v0"
        env = gym.make(env_id)
        env.close()
    except Exception:
        env_id = "MiniGrid-Empty-8x8-v0"
    cmd = [
        sys.executable,
        "-u",
        "scripts/minigrid_learning_curves.py",
        "--env-id",
        env_id,
        "--steps",
        "1000",
        "--seeds",
        "1",
        "--batch-size",
        "64",
        "--capacity",
        "2000",
        "--warmup-steps",
        "500",
        "--eval-interval",
        "1000",
        "--eval-episodes",
        "1",
        "--output",
        str(out_dir),
        "--plot",
        str(plot_dir),
    ]
    env = os.environ.copy()
    env["HIPPO_DEFAULT_DEVICE"] = "cpu"
    proc = subprocess.run(cmd, capture_output=True, text=True, check=True, env=env)
    # Script should print the CSV path and succeed
    assert "wrote learning curves ->" in proc.stdout
