"""Select Network Devices on the map, screenshot the (now populated) subtype
dropdown, then export a filtered PDF to confirm subtypes flow through."""
import os
import json
import urllib.request
from playwright.sync_api import sync_playwright

UI = "http://localhost:5173"
API = "http://localhost:5001/api"
OUT = "/tmp/shopdb-shots"
os.makedirs(OUT, exist_ok=True)


def login():
    body = json.dumps({"username": "270015376", "password": "changeme"}).encode()
    httprequest = urllib.request.Request(f"{API}/auth/login", data=body,
                                 headers={"Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(httprequest))["data"]


def main():
    data = login()
    seed = f"""
      localStorage.setItem('token', {json.dumps(data['access_token'])});
      localStorage.setItem('refreshToken', {json.dumps(data['refresh_token'])});
      localStorage.setItem('user', {json.dumps(json.dumps(data['user']))});
    """
    with sync_playwright() as p:
        browser = p.chromium.launch()
        context = browser.new_context(viewport={"width": 1500, "height": 1000},
                                      accept_downloads=True)
        context.add_init_script(seed)
        page = context.new_page()
        page.goto(f"{UI}/map", wait_until="networkidle", timeout=30000)
        page.wait_for_timeout(1500)

        # First select in the filter bar is the asset-type dropdown.
        type_select = page.locator(".map-filters select").first
        type_select.select_option(value="network_device")
        page.wait_for_timeout(600)

        # Read the subtype dropdown (second select) options.
        subtype_select = page.locator(".map-filters select").nth(1)
        opts = subtype_select.locator("option").all_inner_texts()
        print("SUBTYPE_OPTIONS", opts)

        page.screenshot(path=f"{OUT}/shot_network_subtypes.png", full_page=False)

        # Export a filtered PDF (Network Devices).
        with page.expect_download(timeout=30000) as dl:
            page.get_by_role("button", name="Export PDF").click()
        pdf = f"{OUT}/{dl.value.suggested_filename.replace('.pdf','')}-network.pdf"
        dl.value.save_as(pdf)
        print("SAVED_PDF", pdf)
        browser.close()


if __name__ == "__main__":
    main()
