"""Test credential modal UX: can we select text, copy, interact?"""
import asyncio
from playwright.async_api import async_playwright

BASE = "http://127.0.0.1:5000"

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()

        # Login
        await page.goto(f"{BASE}/login")
        await page.fill('input[name="username"]', 'admin@local.test')
        await page.fill('input[name="password"]', 'Admin123!ChangeMe')
        await page.click('button[type="submit"]')
        await page.wait_for_url("**/inbox**", timeout=5000)
        print("OK: Logged in")

        # Find a ticket with customer_hash
        await page.goto(f"{BASE}/inbox")
        first_link = await page.query_selector('a[href*="/ticket/"]')
        if not first_link:
            print("ERROR: No tickets found")
            await browser.close()
            return
        href = await first_link.get_attribute('href')
        await page.goto(f"{BASE}{href}")
        await page.wait_for_selector('#message-thread', timeout=5000)
        print(f"OK: Opened ticket {href}")

        # Check if customer_hash is set
        cust_hash = await page.evaluate('window._customerHash')
        print(f"OK: customer_hash = '{cust_hash}'")
        if not cust_hash:
            print("SKIP: No customer_hash on this ticket, trying another...")
            await browser.close()
            return

        # Wait for credentials to load
        await page.wait_for_timeout(1500)

        # Click the top-bar cred button
        cred_btn = await page.query_selector('#cred-topbar-btn')
        if not cred_btn:
            print("ERROR: No cred button found")
            await browser.close()
            return
        await cred_btn.click()
        await page.wait_for_timeout(500)

        modal = await page.query_selector('#cred-modal:not(.hidden)')
        print(f"OK: Modal visible = {modal is not None}")

        # Add a test site via API (direct)
        result = await page.evaluate('''async () => {
            const r = await fetch('/api/credentials/' + encodeURIComponent(window._customerHash) + '/sites', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({label: 'test-shop.example.com', url: 'https://test-shop.example.com/admin/'})
            });
            return await r.json();
        }''')
        print(f"OK: Created test site: {result}")
        site_id = result.get('site_id')

        # Add a credential to it via page context
        result2 = await page.evaluate('''async (args) => {
            const r = await fetch('/api/credentials/sites/' + args.siteId + '/creds', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({type: 'backoffice', username: 'admin@test.com', password: 'SuperSecret123!'})
            });
            const text = await r.text();
            try { return JSON.parse(text); } catch(e) { return {error: text.substring(0, 200), status: r.status}; }
        }''', {"siteId": site_id})
        print(f"OK: Created test cred: {result2}")
        cred_id = result2.get('cred_id')

        # Re-open modal to see the credential
        await page.evaluate('showCredentialModal(window._customerHash)')
        await page.wait_for_timeout(1000)

        # Take screenshot of modal
        await page.screenshot(path='/home/agent/data/screenshots/cred_modal_test.png', full_page=False)
        print("OK: Screenshot saved to cred_modal_test.png")

        # Test 1: Can we select username text?
        username_el = await page.query_selector('.font-mono.truncate')
        if username_el:
            text = await username_el.text_content()
            print(f"OK: Username text found: '{text}'")

            # Try to triple-click to select the text
            box = await username_el.bounding_box()
            if box:
                await page.mouse.click(box['x'] + 5, box['y'] + 5, click_count=3)
                selected = await page.evaluate('window.getSelection().toString()')
                print(f"TEST: Text selection after triple-click: '{selected}'")
            else:
                print("WARN: No bounding box for username")
        else:
            print("WARN: No username element found")

        # Test 2: Check if copy button works
        copy_btns = await page.query_selector_all('button[title="Copy username"]')
        if copy_btns:
            print(f"OK: Found {len(copy_btns)} copy username button(s)")
            # Grant clipboard permissions
            ctx = browser.contexts[0]
            await ctx.grant_permissions(['clipboard-read', 'clipboard-write'])
            await copy_btns[0].click()
            await page.wait_for_timeout(500)
            clipboard = await page.evaluate('navigator.clipboard.readText()')
            print(f"TEST: Clipboard after copy button: '{clipboard}'")
        else:
            print("WARN: No copy buttons found")

        # Test 3: Check if reveal works
        reveal_btn = await page.query_selector('button[title="Reveal password"]')
        if reveal_btn:
            await reveal_btn.click()
            await page.wait_for_timeout(500)
            pw_el = await page.query_selector(f'#cred-pw-{cred_id}')
            if pw_el:
                pw_text = await pw_el.text_content()
                print(f"TEST: Revealed password text: '{pw_text}'")
        else:
            print("WARN: No reveal button found")

        # Test 4: Modal interaction - click outside modal content but inside overlay
        await page.mouse.click(10, 10)  # Top-left corner (on the overlay)
        await page.wait_for_timeout(300)
        modal_after = await page.query_selector('#cred-modal:not(.hidden)')
        print(f"TEST: Modal still visible after clicking overlay: {modal_after is not None}")

        # Take final screenshot
        await page.screenshot(path='/home/agent/data/screenshots/cred_modal_test2.png', full_page=False)

        # Cleanup: delete the test site
        await page.evaluate('''async (siteId) => {
            await fetch('/api/credentials/sites/' + siteId, {
                method: 'DELETE',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
                }
            });
        }''', site_id)
        print("OK: Cleaned up test data")

        await browser.close()

asyncio.run(main())
