#!/usr/bin/env python3
"""
Integration tests for mirofish-simulator package.
Validates all exports that InceptBench depends on.
"""

import asyncio
import os
import sys

# Ensure we're testing the installed package, not local source
# Remove local src from path if present
sys.path = [p for p in sys.path if 'mirofish-simulator/src' not in p]


def test_core_imports():
    """Test that all core imports work."""
    print("Testing core imports...")

    from mirofish_simulator import (
        # New agentic architecture
        AgenticOrchestrator,
        AgenticSimulationResult,
        DistractorAgent,
        DistractorAnalysis,
        DistractorMapping,
        StudentModelAgent,
        StudentModel,
        SelectorAgent,
        SelectionResult,
        # InceptBench integration
        MisconceptionAnalyzer,
        ComparativeAnalyzer,
        SUBJECT_TAXONOMIES,
        # Accessibility
        AccessibilityAnalyzer,
    )

    print("  ✓ AgenticOrchestrator")
    print("  ✓ MisconceptionAnalyzer")
    print("  ✓ ComparativeAnalyzer")
    print("  ✓ SUBJECT_TAXONOMIES")
    print("  ✓ AccessibilityAnalyzer")
    print("  ✓ All core imports successful")


def test_version():
    """Test version is correct."""
    print("\nTesting version...")
    import mirofish_simulator
    assert mirofish_simulator.__version__ == "0.8.0", f"Expected 0.8.0, got {mirofish_simulator.__version__}"
    print(f"  ✓ Version: {mirofish_simulator.__version__}")


def test_subject_taxonomies():
    """Test subject taxonomies are available."""
    print("\nTesting subject taxonomies...")
    from mirofish_simulator import SUBJECT_TAXONOMIES

    assert "ap_government" in SUBJECT_TAXONOMIES or "ap government" in SUBJECT_TAXONOMIES
    print(f"  ✓ Available subjects: {list(SUBJECT_TAXONOMIES.keys())[:5]}...")


async def test_agentic_orchestrator():
    """Test the agentic orchestrator works."""
    print("\nTesting AgenticOrchestrator...")
    from mirofish_simulator import AgenticOrchestrator

    # Skip if no API key
    if not os.environ.get("OPENAI_API_KEY"):
        print("  ⚠ Skipped (no OPENAI_API_KEY)")
        return

    orchestrator = AgenticOrchestrator()

    question = {
        "text": "Which branch of the U.S. government makes laws?",
        "options": ["Executive", "Legislative", "Judicial", "Administrative"],
    }

    result = await orchestrator.simulate(
        question=question,
        correct_answer="B",
        grade=8,
        archetype="average_student",
    )

    assert result.selected in ["A", "B", "C", "D"]
    assert result.grade == 8
    assert result.archetype == "average_student"

    print(f"  ✓ Simulation worked: selected={result.selected}, correct={result.is_correct}")


async def test_misconception_analyzer():
    """Test misconception analyzer."""
    print("\nTesting MisconceptionAnalyzer...")
    from mirofish_simulator import MisconceptionAnalyzer

    # Skip if no API key
    if not os.environ.get("OPENAI_API_KEY"):
        print("  ⚠ Skipped (no OPENAI_API_KEY)")
        return

    analyzer = MisconceptionAnalyzer()

    content = {
        "text": "What is 1/2 + 1/4?",
        "options": ["2/6", "3/4", "1/6", "2/4"],
        "correct_answer": "B",
        "subject": "mathematics",
    }

    result = await analyzer.analyze(content)

    assert hasattr(result, "distractors")
    print(f"  ✓ Analysis complete: {len(result.distractors)} distractors analyzed")


def test_accessibility_analyzer():
    """Test accessibility analyzer (no API needed)."""
    print("\nTesting AccessibilityAnalyzer...")
    from mirofish_simulator import AccessibilityAnalyzer

    analyzer = AccessibilityAnalyzer()

    # This should work without API key (deterministic analysis)
    content = {
        "text": "The electoral college is a constitutional mechanism for selecting the president.",
    }
    result = asyncio.run(analyzer.analyze(
        content=content,
        target_grade=5,
    ))

    assert hasattr(result, "reading_level")
    print(f"  ✓ Reading level: Grade {result.reading_level.flesch_kincaid_grade:.1f}")


def main():
    """Run all tests."""
    print("=" * 60)
    print("MiroFish Simulator Integration Tests")
    print("=" * 60)

    try:
        test_core_imports()
        test_version()
        test_subject_taxonomies()
        asyncio.run(test_agentic_orchestrator())
        asyncio.run(test_misconception_analyzer())
        test_accessibility_analyzer()

        print("\n" + "=" * 60)
        print("✓ ALL TESTS PASSED")
        print("=" * 60)
        return 0

    except Exception as e:
        print(f"\n✗ TEST FAILED: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    sys.exit(main())
