#!/usr/bin/env python3
"""
Test plugin discovery and basic integration
"""

import sys
from pathlib import Path

# Add current directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))

def test_plugin_discovery():
    """Test that the plugin system can discover testdrive-jsui."""
    print("🔍 Testing Plugin Discovery")
    print("=" * 50)

    try:
        # Test basic plugin imports
        print("1️⃣ Testing plugin imports...")
        from markitect.plugins import PluginManager, RenderingEngineManager, RenderingConfig
        print("   ✅ Plugin classes imported successfully")

        # Test plugin manager initialization
        print("\n2️⃣ Testing plugin manager initialization...")
        plugin_manager = PluginManager()
        print("   ✅ Plugin manager initialized")

        # Test rendering engine manager
        print("\n3️⃣ Testing rendering engine manager...")
        rendering_manager = RenderingEngineManager(plugin_manager)
        print("   ✅ Rendering engine manager initialized")

        # List available engines
        print("\n4️⃣ Testing engine discovery...")
        engines = rendering_manager.list_engines()
        print(f"   📋 Found engines: {engines}")

        # Test testdrive-jsui specifically
        print("\n5️⃣ Testing testdrive-jsui engine...")
        engine = rendering_manager.get_engine('testdrive-jsui')
        if engine:
            print(f"   ✅ TestDrive JSUI engine found!")
            print(f"   📝 Name: {engine.metadata.name}")
            print(f"   📄 Description: {engine.metadata.description}")
            print(f"   🎯 Supported modes: {engine.get_supported_modes()}")

            # Test render capabilities
            print("\n6️⃣ Testing render capabilities...")
            test_content = "# Test\n\nThis is a test document."

            config = RenderingConfig(
                asset_base_url="_markitect",
                development_mode=False,
                output_directory=Path("/tmp")
            )

            html_output = engine.render_document(test_content, 'edit', config)
            print(f"   ✅ Rendered HTML ({len(html_output):,} characters)")

            # Save test output
            test_file = Path("/tmp/plugin_discovery_test.html")
            test_file.write_text(html_output)
            print(f"   📄 Saved test output: {test_file}")

        else:
            print("   ❌ TestDrive JSUI engine not found")
            return False

        print(f"\n🎉 Plugin discovery test completed successfully!")
        return True

    except Exception as e:
        print(f"❌ Plugin discovery test failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = test_plugin_discovery()
    sys.exit(0 if success else 1)