#!/usr/bin/env python3
"""
Create a browser-ready test file to verify JavaScript fixes
"""

import sys
from pathlib import Path

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

def create_browser_test():
    """Create a complete test file ready for browser verification."""

    print("🌐 Creating Browser-Ready Test")
    print("=" * 50)

    try:
        from markitect.plugins import PluginManager, RenderingEngineManager, RenderingConfig

        # Initialize plugin system
        plugin_manager = PluginManager()
        rendering_manager = RenderingEngineManager(plugin_manager)
        engine = rendering_manager.get_engine('testdrive-jsui')

        # Test content specifically for JavaScript verification
        test_content = """# JavaScript Fix Verification

This document tests the resolved JavaScript issues:

## Fixed Issues ✅

### 1. Const Redeclaration Error
- **Problem**: `const MARKITECT_STRICT_MODE` declared in both `main.js` and `control-base.js`
- **Solution**: Removed duplicate declaration from `control-base.js`, now declared only in `main-updated.js`

### 2. MarkitectMain Not Available
- **Problem**: Loading `main.js` instead of `main-updated.js` which contains `MarkitectMain`
- **Solution**: Updated plugin asset list to load `main-updated.js`

### 3. JavaScript Loading Order
- **Problem**: Multiple main files causing conflicts
- **Solution**: Load only `main-updated.js` with all required functionality

## Expected Browser Behavior

When you open this document in a browser:

1. ✅ **No console errors** about const redeclaration
2. ✅ **MarkitectMain available** - edit functionality should work
3. ✅ **Control panels should appear** in compass positions:
   - Northwest: Table of Contents
   - Northeast: Edit Controls
   - East: Status Information
   - Southeast: Debug Panel

## Test Instructions

1. Open this HTML file in a browser
2. Check the browser console (F12 → Console tab)
3. Look for:
   - ❌ No "redeclaration of const" errors
   - ✅ "🎯 TestDrive JSUI loading complete, initializing..."
   - ✅ "🚀 Starting MarkitectMain initialization..."
   - ✅ Various initialization success messages

## Interactive Testing

Try clicking on different sections of this document - they should become editable if JavaScript is working correctly.

---

**Generated**: {timestamp}
**Engine**: testdrive-jsui
**Assets**: All plugin assets deployed to `_markitect/plugins/testdrive-jsui/`
"""

        # Create output directory
        output_dir = Path('/tmp/browser_test_verification')
        output_dir.mkdir(exist_ok=True)

        print(f"📁 Output directory: {output_dir}")

        # Configure rendering
        config = RenderingConfig(
            asset_base_url="_markitect",
            development_mode=False,
            output_directory=output_dir
        )

        # Deploy assets
        print(f"📦 Deploying assets...")
        deployed_assets = rendering_manager.deploy_engine_assets('testdrive-jsui', config)

        asset_count = sum(len(files) for files in deployed_assets.values() if isinstance(files, list))
        print(f"   ✅ Deployed {asset_count} assets")

        # Add timestamp to content
        from datetime import datetime
        timestamped_content = test_content.format(
            timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        )

        # Render document
        print(f"📄 Rendering test document...")
        html_content = engine.render_document(timestamped_content, 'edit', config)

        # Write test file
        test_file = output_dir / 'browser_verification_test.html'
        test_file.write_text(html_content)

        print(f"✅ Browser test file created!")
        print(f"\n🎯 Instructions:")
        print(f"1. Open: file://{test_file.absolute()}")
        print(f"2. Check browser console for errors")
        print(f"3. Look for edit functionality (click sections to edit)")
        print(f"4. Control panels should appear around the document")

        print(f"\n📊 File Details:")
        print(f"   Size: {len(html_content):,} characters")
        print(f"   Assets: {asset_count} files deployed")
        print(f"   Location: {test_file}")

        return True

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

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