"""GUI accounts tests — account creation form, list, management."""

import asyncio
import pytest
from playwright.async_api import Error as PlaywrightError
from playwright.async_api import async_playwright


@pytest.fixture
async def browser():
    """Launch Playwright browser."""
    async with async_playwright() as p:
        try:
            browser = await p.chromium.launch(headless=True)
        except PlaywrightError as e:
            pytest.skip(str(e))
        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 TestDashboardAccounts:
    """Test account creation form functionality."""

    async def test_account_creation_form(self, page, server):
        """Test account creation form functionality."""
        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 class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Accounts</h3>
                        <button id="add-account-btn" class="px-3 py-1.5 border border-dashed border-gray-300 rounded text-sm text-gray-500 hover:border-blue-400 hover:text-blue-600 w-full">+ Add Account</button>
                        <div id="account-form" class="hidden mt-4 p-4 bg-blue-50 rounded-lg space-y-2">
                            <input id="account-name" class="px-2 py-1.5 border rounded text-sm" placeholder="Account name" type="text">
                            <select id="account-provider" class="px-2 py-1.5 border rounded text-sm">
                                <option value="anthropic">anthropic</option>
                                <option value="openai">openai</option>
                                <option value="google">google</option>
                            </select>
                            <input id="api-key" class="px-2 py-1.5 border rounded text-sm" placeholder="API Key" type="password">
                            <input id="daily-budget" class="px-2 py-1.5 border rounded text-sm" placeholder="Daily budget $" type="number" value="5">
                            <input id="monthly-budget" class="px-2 py-1.5 border rounded text-sm" placeholder="Monthly budget $" type="number" value="60">
                            <div class="flex gap-2">
                                <button id="create-account-btn" class="px-3 py-1.5 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">Create</button>
                                <button id="cancel-btn" class="px-3 py-1.5 bg-gray-200 text-gray-700 rounded text-sm">Cancel</button>
                            </div>
                        </div>
                        <div id="accounts-list"></div>
                    </div>
                </main>
            </div>
            <script>
                let accounts = [];
                
                document.getElementById('add-account-btn').addEventListener('click', () => {
                    document.getElementById('account-form').classList.remove('hidden');
                    document.getElementById('add-account-btn').classList.add('hidden');
                });
                
                document.getElementById('cancel-btn').addEventListener('click', () => {
                    document.getElementById('account-form').classList.add('hidden');
                    document.getElementById('add-account-btn').classList.remove('hidden');
                    document.getElementById('account-name').value = '';
                    document.getElementById('api-key').value = '';
                });
                
                document.getElementById('create-account-btn').addEventListener('click', () => {
                    const name = document.getElementById('account-name').value;
                    const provider = document.getElementById('account-provider').value;
                    const apiKey = document.getElementById('api-key').value;
                    
                    if (name && apiKey) {
                        accounts.push({ name, provider, id: Date.now() });
                        updateAccountsList();
                        
                        document.getElementById('account-form').classList.add('hidden');
                        document.getElementById('add-account-btn').classList.remove('hidden');
                        document.getElementById('account-name').value = '';
                        document.getElementById('api-key').value = '';
                    }
                });
                
                function updateAccountsList() {
                    const list = document.getElementById('accounts-list');
                    list.innerHTML = accounts.map(acc => 
                        `<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                            <div>
                                <span class="font-medium text-sm">${acc.name}</span>
                                <span class="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs ml-2">${acc.provider}</span>
                            </div>
                        </div>`
                    ).join('');
                }
            </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")
        
        # Click add account button
        await page.click("#add-account-btn")
        form_visible = await page.locator("#account-form").is_visible()
        assert form_visible is True
        
        # Fill form
        await page.fill("#account-name", "Test Account")
        await page.select_option("#account-provider", "anthropic")
        await page.fill("#api-key", "sk-ant-test123")
        
        # Create account
        await page.click("#create-account-btn")
        
        # Wait a moment for the form to hide and account to be added
        await page.wait_for_timeout(500)
        
        # Verify account appears in list
        accounts_text = await page.locator("#accounts-list").inner_text()
        assert "Test Account" in accounts_text
        assert "anthropic" in accounts_text
        
        # Check if form has the 'hidden' class
        form_class = await page.locator("#account-form").get_attribute("class")
        assert "hidden" in form_class
        button_visible = await page.locator("#add-account-btn").is_visible()
        assert button_visible is True

    async def test_accounts_list_displays_correctly(self, page, server):
        """Test accounts list displays with mock data."""
        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="accounts-panel">
                        <h3 class="text-sm font-semibold text-gray-900 mb-3">Accounts</h3>
                        <div id="accounts-list"></div>
                    </div>
                </main>
            </div>
            <script>
                const accounts = [
                    { name: "Work Anthropic", provider: "anthropic", daily_cost: 1.23, monthly_cost: 45.67 },
                    { name: "OpenRouter Free", provider: "openrouter", daily_cost: 0, monthly_cost: 0 },
                ];
                
                const list = document.getElementById('accounts-list');
                list.innerHTML = accounts.map(acc => 
                    `<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                        <div>
                            <span class="font-medium text-sm">${acc.name}</span>
                            <span class="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs ml-2">${acc.provider}</span>
                        </div>
                        <div class="text-right">
                            <div class="text-sm">$${acc.daily_cost.toFixed(2)} today</div>
                            <div class="text-xs text-gray-500">$${acc.monthly_cost.toFixed(2)} this month</div>
                        </div>
                    </div>`
                ).join('');
            </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 accounts are displayed
        accounts_text = await page.locator("#accounts-list").inner_text()
        assert "Work Anthropic" in accounts_text
        assert "anthropic" in accounts_text
        assert "OpenRouter Free" in accounts_text
        assert "$1.23 today" in accounts_text
