"""Optional Chromium test. Install Python Playwright and set CHROMIUM to the browser executable."""
import base64
import os
import pathlib
import secrets
import shutil
import socket
import subprocess
import tempfile
import time
import urllib.parse
import zipfile

from playwright.sync_api import sync_playwright

ROOT = pathlib.Path(__file__).resolve().parents[1]
OWNER = 'majorvehicles@gmail.com'


def check_home_categories(page, origin, width):
    for language in ['en', 'es']:
        page.goto(origin+'/?lang='+language)
        vehicles = page.locator('#homeCatalog').evaluate('(el) => JSON.parse(el.textContent).active')
        expected = {bus['stock'] for bus in vehicles if not bus['wc']}
        cards = page.locator('#fleetGrid [data-card-stock]')
        if width <= 720:
            choices = page.locator('[name="quickCategory"]')
            assert choices.count() == 3 and choices.first.is_checked()
            assert page.locator('#quickResults').is_visible()
            choices.locator('..').nth(2).click()
        else:
            links = page.locator('.hero-inventory-links a')
            assert links.count() == 3 and all(link.is_visible() for link in links.all())
            assert 'wheelchair-bus-and-wheelchair-vans' in links.nth(1).get_attribute('href')
            links.last.click()
        assert set(cards.evaluate_all('(rows) => rows.map(row => row.dataset.cardStock)')) == expected
        assert page.locator('#bubbleRow [data-cat=other]').get_attribute('aria-pressed') == 'true'
        page.locator('#bubbleRow [data-cat=all]').click()
        assert cards.count() == len(vehicles)


def smoke():
    with tempfile.TemporaryDirectory() as temp:
        working = pathlib.Path(temp)
        storage = working / 'storage'
        for directory in ['logs','app/private/photos','framework/cache/data','framework/sessions','framework/views']:
            (storage / directory).mkdir(parents=True)
        with socket.socket() as probe:
            probe.bind(('127.0.0.1', 0))
            port = probe.getsockname()[1]
        origin = f'http://127.0.0.1:{port}'
        env = {**os.environ, 'APP_ENV':'testing', 'APP_URL':origin, 'APP_DEBUG':'false',
               'APP_KEY':'base64:'+base64.b64encode(secrets.token_bytes(32)).decode(),
               'DB_DATABASE':str(working/'browser.sqlite'), 'LARAVEL_STORAGE_PATH':str(storage),
               'CACHE_STORE':'file','SESSION_DRIVER':'file','SESSION_SECURE_COOKIE':'false'}
        password = secrets.token_urlsafe(24)
        for args, inp in [(['dealer:install'],None), (['dealer:user',OWNER,'owner'],password+'\n')]:
            subprocess.run(['php','artisan',*args],env=env,cwd=ROOT,input=inp,text=True,check=True,stdout=subprocess.DEVNULL)
        with open(working/'server.log','w') as server_log:
            server = subprocess.Popen(['php','-S',f'127.0.0.1:{port}','-t','public','tests/router.php'],
                                        env=env,cwd=ROOT,stdout=server_log,stderr=server_log)
            try:
                for _ in range(100):
                    try:
                        with socket.create_connection(('127.0.0.1',port),timeout=.1): break
                    except OSError: time.sleep(.05)
                with sync_playwright() as automation:
                    browser = automation.chromium.launch(executable_path=os.getenv('CHROMIUM') or shutil.which('chromium'),
                                                         args=['--no-sandbox','--disable-dev-shm-usage'])
                    for width, height in [(1440,900),(390,844)]:
                        context = browser.new_context(viewport={'width':width,'height':height},accept_downloads=True)
                        context.route('**/*',lambda route: route.continue_() if urllib.parse.urlsplit(route.request.url).hostname in ('127.0.0.1',None) else route.abort())
                        page = context.new_page()
                        page.set_default_timeout(12000)
                        errors = []
                        page.on('pageerror',lambda err:errors.append(str(err)))
                        check_home_categories(page, origin, width)
                        page.goto(origin+'/')
                        assert page.locator('#fleetGrid').count() == 1
                        assert page.evaluate('document.documentElement.scrollWidth <= innerWidth+2'),('home overflow',width)
                        listing = '/inventory/a5352/'
                        page.goto(origin+listing)
                        assert page.locator('h1').is_visible()
                        assert page.evaluate('document.documentElement.scrollWidth <= innerWidth+2'),('listing overflow',width)
                        photo = page.locator('button[data-photo="1"]').first
                        photo.click()
                        page.locator('[data-inquire]:visible').first.click()
                        buyer = 'Laravel Test '+str(width)
                        page.locator('#crmInquiry [name=name]').fill(buyer)
                        page.locator('#crmInquiry [name=email]').fill(f'buyer-{width}@example.invalid')
                        page.locator('#crmInquiry [name=question]').fill('Can we schedule an inspection?')
                        page.locator('#crmInquiry button[type=submit]').click()
                        page.wait_for_function("document.getElementById('crmInquiryStatus').innerText.includes('#')")
                        receipt = page.locator('#crmInquiryStatus').inner_text()
                        assert 'ticket' in receipt.lower(),receipt
                        page.goto(origin+'/sales/staff.html')
                        assert '/auth/sign-in' in page.url
                        page.locator('[name=login]').fill(OWNER)
                        page.locator('[name=password]').fill(password)
                        page.locator('button[type=submit],button:not([type])').first.click()
                        page.locator('#desk').wait_for(state='visible')
                        page.locator('#search').fill(buyer)
                        page.get_by_text(buyer,exact=True).first.wait_for(state='visible')
                        with page.expect_download() as download:
                            page.locator('#export').click()
                        workbook = download.value.path()
                        with zipfile.ZipFile(workbook) as excel:
                            assert excel.testzip() is None
                            assert 'xl/workbook.xml' in excel.namelist()
                            assert any(buyer.encode() in excel.read(path) for path in excel.namelist() if path.startswith('xl/') and path.endswith('.xml'))
                        page.goto(origin+'/sales/inventory.html')
                        page.locator('#listSearch').fill('A5352')
                        page.locator('.desk-row:visible').filter(has_text='A5352').first.wait_for()
                        page.goto(origin+'/es/inventory/a5352/')
                        assert page.locator('html').get_attribute('lang')=='es'
                        assert not errors,errors
                        context.close()
                        print(f'PASS Chromium {width}×{height}: buyer inquiry on A5352, receipt, staff login, ticket search, workbook contents, inventory search and Spanish listing.',flush=True)
                    browser.close()
            finally:
                server.terminate()
                server.wait(timeout=10)


if __name__ == '__main__':
    smoke()
