"""Tests for the plugin system."""

import tempfile
from pathlib import Path

import numpy as np

from orbit.plugins import BaseAnalyzer, AnalyzerResult, discover_plugins, run_plugins


def test_discover_empty_dir():
    with tempfile.TemporaryDirectory() as tmpdir:
        plugins = discover_plugins(Path(tmpdir))
        assert plugins == []


def test_discover_nonexistent_dir():
    plugins = discover_plugins(Path("/nonexistent/path/12345"))
    assert plugins == []


def test_discover_and_run_plugin():
    with tempfile.TemporaryDirectory() as tmpdir:
        plugin_file = Path(tmpdir) / "test_analyzer.py"
        plugin_file.write_text("""
from orbit.plugins import BaseAnalyzer, AnalyzerResult

class TestAnalyzer(BaseAnalyzer):
    name = "test_metric"
    description = "A test analyzer"

    def analyze(self, action_episodes, info=None, **kwargs):
        return AnalyzerResult(
            name=self.name,
            score=0.9,
            status="ok",
            summary="All good",
            details={"count": len(action_episodes)},
        )
""")
        plugins = discover_plugins(Path(tmpdir))
        assert len(plugins) == 1
        assert plugins[0].name == "test_metric"

        # Run plugins
        episodes = [np.random.randn(10, 6) for _ in range(5)]
        results = run_plugins(episodes, plugins_dir=Path(tmpdir))
        assert len(results) == 1
        assert results[0].score == 0.9
        assert results[0].details["count"] == 5


def test_broken_plugin_handled_gracefully():
    with tempfile.TemporaryDirectory() as tmpdir:
        plugin_file = Path(tmpdir) / "broken.py"
        plugin_file.write_text("""
from orbit.plugins import BaseAnalyzer, AnalyzerResult

class BrokenAnalyzer(BaseAnalyzer):
    name = "broken"

    def analyze(self, action_episodes, info=None, **kwargs):
        raise ValueError("intentional error")
""")
        episodes = [np.random.randn(10, 6)]
        results = run_plugins(episodes, plugins_dir=Path(tmpdir))
        assert len(results) == 1
        assert results[0].status == "bad"
        assert "intentional error" in results[0].summary
