#!/usr/bin/env python3
"""
RoboPhD Smoke Test - Verify basic functionality works
"""

from datetime import datetime
import sys
import os
from pathlib import Path
from RoboPhD.core import resolve_api_key

# Add RoboPhD to path
sys.path.insert(0, str(Path.cwd()))

def test_imports():
    """Test that all RoboPhD modules can be imported."""
    print("Testing imports...")
    
    try:
        from RoboPhD import (
            SQLGenerator, 
            Evaluator, 
            DatabaseManager,
            AgentOrchestrator,
            ParallelAgentResearcher,
            ParallelAgentEvolver
        )
        print("✅ All imports successful")
        return True
    except ImportError as e:
        print(f"❌ Import failed: {e}")
        return False


def test_basic_initialization():
    """Test basic initialization of components."""
    print("\nTesting basic initialization...")
    
    try:
        from RoboPhD.core import DatabaseManager
        from RoboPhD.evolution import EvolutionStrategySelector
        from RoboPhD.config import SUPPORTED_MODELS
        
        # Test DatabaseManager
        db_root = Path("benchmark_resources/datasets/test/test/test_databases")
        if db_root.exists():
            databases = DatabaseManager.get_databases(db_root)
            print(f"✅ DatabaseManager found {len(databases)} databases")
        else:
            print("⚠️ Train dataset not available, skipping database test")
        
        # Test EvolutionStrategySelector
        selector = EvolutionStrategySelector()
        strategies = selector.list_strategies()
        print(f"✅ EvolutionStrategySelector found {len(strategies)} strategies")
        
        # Test config
        print(f"✅ Config has {len(SUPPORTED_MODELS)} supported models")
        
        return True
    except Exception as e:
        print(f"❌ Initialization failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_researcher_help():
    """Test that researcher.py can show help."""
    print("\nTesting researcher.py help...")
    
    try:
        import subprocess
        result = subprocess.run(
            ["python", "RoboPhD/researcher.py", "--help"],
            capture_output=True,
            text=True,
            timeout=5
        )
        
        if result.returncode == 0 and "RoboPhD Parallel Agent Research System" in result.stdout:
            print("✅ researcher.py help works")
            return True
        else:
            print(f"❌ researcher.py help failed")
            if result.stderr:
                print(f"   Error: {result.stderr[:200]}")
            return False
    except Exception as e:
        print(f"❌ Failed to run researcher.py: {e}")
        return False


def test_minimal_run():
    """Test a minimal research run (dry run without Claude)."""
    print("\nTesting minimal run setup (this will take minutes, be patient!)...")
    
    try:
        from RoboPhD.researcher import ParallelAgentResearcher

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        experiment_name = f"smoketest_{timestamp}"

        api_key = resolve_api_key()
        
        # Create researcher with minimal config
        researcher = ParallelAgentResearcher(
            dataset='test',
            num_iterations=1,
            agents_per_iteration=1,
            databases_per_iteration=1,
            questions_per_database=2,
            eval_model='haiku-3.5',
            analysis_model='haiku-3.5',
            evolution_model='haiku-3.5',
            max_concurrent_dbs=1,
            random_seed=42,
            api_key=api_key
        )
        researcher.run(initial_agents=["minimal_3a"])
        
        # Check that it initialized
        if researcher.experiment_dir.exists():
            print(f"✅ Researcher initialized with directory: {researcher.experiment_dir}")
            
            # Clean up
            import shutil
            shutil.rmtree(researcher.experiment_dir)
            
            return True
        else:
            print("❌ Researcher failed to create experiment directory")
            return False
            
    except Exception as e:
        print(f"❌ Minimal run setup failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all smoke tests."""
    print("="*60)
    print("RoboPhD SMOKE TEST SUITE")
    print("="*60)
    
    tests = [
        ("Imports", test_imports),
        ("Basic Initialization", test_basic_initialization),
        ("Researcher Help", test_researcher_help),
        ("Minimal Run Setup", test_minimal_run)
    ]
    
    results = []
    for test_name, test_func in tests:
        print(f"\n🧪 Running: {test_name}")
        print("-"*40)
        success = test_func()
        results.append((test_name, success))
    
    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)
    
    passed = sum(1 for _, success in results if success)
    total = len(results)
    
    for test_name, success in results:
        status = "✅ PASS" if success else "❌ FAIL"
        print(f"{test_name:.<40} {status}")
    
    print(f"\nOverall: {passed}/{total} tests passed")
    
    if passed == total:
        print("\n🎉 ALL SMOKE TESTS PASSED!")
        return 0
    else:
        print(f"\n⚠️ {total - passed} test(s) failed")
        return 1


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