#!/usr/bin/env python3
"""
Test CLI integration with asset deployment
"""

import sys
from pathlib import Path
import shutil

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

def test_cli_with_asset_deployment():
    """Test CLI integration with complete asset deployment."""

    print("🚀 Testing CLI Integration with Asset Deployment")
    print("=" * 60)

    try:
        # Clean up and create test output directory
        output_dir = Path('/tmp/test_cli_assets')
        if output_dir.exists():
            shutil.rmtree(output_dir)
        output_dir.mkdir()

        # Test markdown content
        test_content = """# CLI Asset Deployment Test

This document verifies that the CLI properly deploys plugin assets.

## Test Scenarios

### JavaScript Assets
- Core systems (debug, section management)
- UI components (panels, controls)
- Main application entry point

### CSS Assets
- Base editor styles
- Control panel styles
- GitHub theme

### Images
- Control icons (edit, save, reset)

## Expected Results
All assets should be deployed to `_markitect/plugins/testdrive-jsui/` directory.
"""

        # Write test file
        input_file = output_dir / 'test_input.md'
        input_file.write_text(test_content)
        output_file = output_dir / 'test_output.html'

        print(f"📝 Created test input: {input_file}")

        # Import CLI function logic
        from markitect.plugins import PluginManager, RenderingEngineManager, RenderingConfig

        # Simulate CLI logic for plugin-based rendering
        print("\n1️⃣ Simulating CLI plugin rendering...")

        # Initialize plugin system (same as CLI)
        plugin_manager = PluginManager()
        rendering_manager = RenderingEngineManager(plugin_manager)

        # Engine selection (same as CLI default logic)
        engine_name = 'testdrive-jsui'  # Default for edit mode
        rendering_engine = rendering_manager.get_engine(engine_name)

        if not rendering_engine:
            print(f"   ❌ Engine '{engine_name}' not found")
            return False

        print(f"   ✅ Using engine: {engine_name}")

        # Read content (same as CLI)
        content = input_file.read_text(encoding='utf-8')

        # Configure rendering (same as CLI)
        render_config = RenderingConfig(
            asset_base_url="_markitect",
            development_mode=False,  # Production deployment for CLI usage
            output_directory=output_file.parent
        )

        # Render document (same as CLI)
        html_content = rendering_engine.render_document(content, 'edit', render_config)

        # Deploy assets (same as CLI)
        print(f"\n2️⃣ Deploying assets...")
        deployed_assets = rendering_manager.deploy_engine_assets(engine_name, render_config)

        # Report deployment results
        total_assets = sum(len(files) for files in deployed_assets.values() if isinstance(files, list))
        print(f"   📄 Deployed {total_assets} asset files")

        for asset_type, files in deployed_assets.items():
            if isinstance(files, list) and files:
                print(f"   {asset_type}: {len(files)} files")

        # Write HTML output (same as CLI)
        output_file.write_text(html_content, encoding='utf-8')
        output_size = output_file.stat().st_size

        print(f"\n3️⃣ HTML output written:")
        print(f"   📄 File: {output_file}")
        print(f"   📊 Size: {output_size:,} bytes")

        # Verify asset references in HTML
        print(f"\n4️⃣ Verifying asset references in HTML...")

        # Check for CSS references
        css_refs = []
        js_refs = []

        for line in html_content.split('\n'):
            if 'href=' in line and '.css' in line:
                css_refs.append(line.strip())
            elif 'src=' in line and '.js' in line and 'plugins/testdrive-jsui' in line:
                js_refs.append(line.strip())

        print(f"   🎨 CSS references: {len(css_refs)}")
        for ref in css_refs[:3]:
            print(f"      {ref}")
        if len(css_refs) > 3:
            print(f"      ... and {len(css_refs) - 3} more")

        print(f"   📜 JS references: {len(js_refs)}")
        for ref in js_refs[:3]:
            print(f"      {ref}")
        if len(js_refs) > 3:
            print(f"      ... and {len(js_refs) - 3} more")

        # Verify actual asset files exist
        print(f"\n5️⃣ Verifying deployed files exist...")

        asset_base = output_dir / "_markitect" / "plugins" / "testdrive-jsui"
        if not asset_base.exists():
            print(f"   ❌ Asset base directory missing: {asset_base}")
            return False

        # Count deployed files by type
        js_files = list((asset_base / "static" / "js").rglob("*.js")) if (asset_base / "static" / "js").exists() else []
        css_files = list((asset_base / "static" / "css").rglob("*.css")) if (asset_base / "static" / "css").exists() else []
        img_files = list((asset_base / "images").rglob("*")) if (asset_base / "images").exists() else []

        print(f"   ✅ Deployed files verified:")
        print(f"      JavaScript: {len(js_files)} files")
        print(f"      CSS: {len(css_files)} files")
        print(f"      Images: {len(img_files)} files")

        # Test asset accessibility
        print(f"\n6️⃣ Testing asset accessibility...")

        missing_assets = 0
        for asset_type, asset_list in rendering_engine.get_required_assets().items():
            if asset_type == 'external':
                continue

            for asset_path in asset_list:
                full_asset_path = asset_base / asset_path
                if not full_asset_path.exists():
                    print(f"   ❌ Missing: {asset_path}")
                    missing_assets += 1

        if missing_assets == 0:
            print(f"   ✅ All required assets are accessible")
        else:
            print(f"   ⚠️ {missing_assets} assets missing")

        print(f"\n🎉 CLI asset deployment test completed!")
        print(f"\n📊 Summary:")
        print(f"   Input: {input_file} ({len(content)} chars)")
        print(f"   Output: {output_file} ({output_size:,} bytes)")
        print(f"   Assets: {total_assets} files deployed")
        print(f"   🌐 Open: file://{output_file.absolute()}")

        return missing_assets == 0

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

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