"""GUI component tests — connection status, responsive design, VMs."""

import asyncio
import pytest
from playwright.async_api import async_playwright


@pytest.fixture
async def browser():
    """Launch Playwright browser."""
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        yield browser
        await browser.close()


@pytest.fixture
async def page(browser):
    """Create a new page."""
    page = await browser.new_page()
    yield page
    await page.close()


@pytest.fixture
async def server():
    """Start the test server."""
    import threading
    import uvicorn
    import socket
    import time
    from unittest.mock import patch
    
    with patch.dict("os.environ", {
        "AI_PROXY_MASTER_KEY": "sk-test-e2e",
        "ANTHROPIC_API_KEY": "sk-ant-test",
        "REDIS_URL": "redis://localhost:6379/0",
    }):
        from proxym.main import app
        
        # Find a free port
        sock = socket.socket()
        sock.bind(("", 0))
        port = sock.getsockname()[1]
        sock.close()
        
        server_url = f"http://localhost:{port}"
        
        def run_server():
            uvicorn.run(app, host="localhost", port=port, log_level="error")
        
        thread = threading.Thread(target=run_server, daemon=True)
        thread.start()
        
        # Wait for server to be ready
        time.sleep(2)
        
        yield server_url


class TestDashboardComponents:
    """Test dashboard UI components."""

    async def test_connection_status(self, page, server):
        """Test connection status indicator."""
        dashboard_html = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>AI Proxy Dashboard</title>
            <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body>
            <div class="min-h-screen bg-gray-50">
                <header class="bg-white border-b border-gray-200 px-6 py-3">
                    <div class="flex items-center justify-between max-w-7xl mx-auto">
                        <h1 class="text-lg font-semibold text-gray-900">AI Proxy Dashboard</h1>
                        <div class="flex items-center gap-4">
                            <span id="status-badge" class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">Disconnected</span>
                            <button id="refresh-btn" class="px-2 py-1 bg-gray-100 rounded text-xs hover:bg-gray-200">Refresh</button>
                        </div>
                    </div>
                </header>
                <main class="max-w-7xl mx-auto px-6 py-6">
                    <div id="connection-info">Not connected</div>
                </main>
            </div>
            <script>
                let connected = false;
                
                function updateConnectionStatus(isConnected) {
                    connected = isConnected;
                    const badge = document.getElementById('status-badge');
                    const info = document.getElementById('connection-info');
                    
                    if (isConnected) {
                        badge.className = 'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-emerald-100 text-emerald-800';
                        badge.textContent = 'Connected';
                        info.textContent = 'Connected to proxy server';
                    } else {
                        badge.className = 'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800';
                        badge.textContent = 'Disconnected';
                        info.textContent = 'Not connected to proxy server';
                    }
                }
                
                document.getElementById('refresh-btn').addEventListener('click', () => {
                    setTimeout(() => {
                        updateConnectionStatus(true);
                    }, 500);
                });
                
                updateConnectionStatus(false);
            </script>
        </body>
        </html>
        """
        
        await page.route("**/*", lambda route: route.fulfill(
            status=200,
            body=dashboard_html,
            headers={"Content-Type": "text/html"}
        ))
        
        await page.goto(server)
        await page.wait_for_load_state("networkidle")
        
        # Check initial disconnected status
        badge_text = await page.locator("#status-badge").inner_text()
        assert "Disconnected" in badge_text
        badge_class = await page.locator("#status-badge").get_attribute("class")
        assert "bg-red-100" in badge_class
        connection_text = await page.locator("#connection-info").inner_text()
        assert "Not connected" in connection_text
        
        # Click refresh to simulate connection
        await page.click("#refresh-btn")
        
        # Wait for status update
        await page.wait_for_timeout(600)
        
        # Check connected status
        badge_text = await page.locator("#status-badge").inner_text()
        assert "Connected" in badge_text
        badge_class = await page.locator("#status-badge").get_attribute("class")
        assert "bg-emerald-100" in badge_class
        connection_text = await page.locator("#connection-info").inner_text()
        assert "Connected to proxy server" in connection_text

    async def test_responsive_design(self, page, server):
        """Test dashboard responsive design on different screen sizes."""
        dashboard_html = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>AI Proxy Dashboard</title>
            <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body>
            <div class="min-h-screen bg-gray-50">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 p-6">
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Card 1</h3>
                        <p>Content 1</p>
                    </div>
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Card 2</h3>
                        <p>Content 2</p>
                    </div>
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Card 3</h3>
                        <p>Content 3</p>
                    </div>
                </div>
            </div>
        </body>
        </html>
        """
        
        await page.route("**/*", lambda route: route.fulfill(
            status=200,
            body=dashboard_html,
            headers={"Content-Type": "text/html"}
        ))
        
        await page.goto(server)
        await page.wait_for_load_state("networkidle")
        
        # Test mobile view
        await page.set_viewport_size({"width": 375, "height": 667})
        cards = await page.locator(".grid > div").count()
        assert cards == 3
        
        # Check that cards are stacked vertically on mobile
        first_card = await page.locator(".grid > div").first.bounding_box()
        second_card = await page.locator(".grid > div").nth(1).bounding_box()
        assert second_card["y"] > first_card["y"] + first_card["height"]
        
        # Test desktop view
        await page.set_viewport_size({"width": 1200, "height": 800})
        await page.wait_for_load_state("networkidle")
        
        # Check grid layout on desktop
        grid_width = await page.locator(".grid").evaluate("el => el.offsetWidth")
        assert grid_width > 800  # Should be wider on desktop

    async def test_vms_panel_display(self, page, server):
        """Test VMs panel displays correctly."""
        dashboard_html = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>AI Proxy Dashboard</title>
            <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body>
            <div class="min-h-screen bg-gray-50">
                <main class="max-w-7xl mx-auto px-6 py-6">
                    <div id="vms-panel">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Virtual Machines</h3>
                        <div id="vms-list">
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                                <div>
                                    <span class="font-medium text-sm">windsurf-work</span>
                                    <span class="px-1.5 py-0.5 bg-emerald-100 text-emerald-700 rounded text-xs ml-2">running</span>
                                </div>
                                <div class="flex gap-1">
                                    <button class="px-2 py-1 rounded text-xs bg-red-100 text-red-700 hover:bg-red-200">Stop</button>
                                </div>
                            </div>
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                                <div>
                                    <span class="font-medium text-sm">cursor-dev</span>
                                    <span class="px-1.5 py-0.5 bg-gray-100 text-gray-700 rounded text-xs ml-2">stopped</span>
                                </div>
                                <div class="flex gap-1">
                                    <button class="px-2 py-1 rounded text-xs bg-emerald-100 text-emerald-700 hover:bg-emerald-200">Start</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </main>
            </div>
        </body>
        </html>
        """
        
        await page.route("**/*", lambda route: route.fulfill(
            status=200,
            body=dashboard_html,
            headers={"Content-Type": "text/html"}
        ))
        
        await page.goto(server)
        await page.wait_for_load_state("networkidle")
        
        # Check VMs are displayed
        vms_text = await page.locator("#vms-list").inner_text()
        assert "windsurf-work" in vms_text
        assert "running" in vms_text
        assert "cursor-dev" in vms_text
        assert "stopped" in vms_text
        
        # Check action buttons
        assert await page.locator("button:has-text('Stop')").count() > 0
        assert await page.locator("button:has-text('Start')").count() > 0

    async def test_models_panel_display(self, page, server):
        """Test models panel displays correctly."""
        dashboard_html = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>AI Proxy Dashboard</title>
            <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body>
            <div class="min-h-screen bg-gray-50">
                <main class="max-w-7xl mx-auto px-6 py-6">
                    <div id="models-panel">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Available Models (5)</h3>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500">Model</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500">Provider</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500">Input $/1M</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-500">Output $/1M</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="border-t border-gray-100">
                                        <td class="px-3 py-2">claude-3-haiku</td>
                                        <td class="px-3 py-2">anthropic</td>
                                        <td class="px-3 py-2">$0.25</td>
                                        <td class="px-3 py-2">$1.25</td>
                                    </tr>
                                    <tr class="border-t border-gray-100">
                                        <td class="px-3 py-2">gpt-3.5-turbo</td>
                                        <td class="px-3 py-2">openai</td>
                                        <td class="px-3 py-2">$0.50</td>
                                        <td class="px-3 py-2">$1.50</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </main>
            </div>
        </body>
        </html>
        """
        
        await page.route("**/*", lambda route: route.fulfill(
            status=200,
            body=dashboard_html,
            headers={"Content-Type": "text/html"}
        ))
        
        await page.goto(server)
        await page.wait_for_load_state("networkidle")
        
        # Check models table is displayed
        models_text = await page.locator("#models-panel").inner_text()
        assert "claude-3-haiku" in models_text
        assert "anthropic" in models_text
        assert "gpt-3.5-turbo" in models_text
        assert "$0.25" in models_text
