"""Autonomous test: draw a line on the Field Capture canvas and verify the
measurement modal opens. Captures console logs for troubleshooting."""
import json
import sys
import time
import os

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

sys.stdout.reconfigure(encoding="utf-8", errors="replace")

BASE = "http://localhost:8000/field-capture.html?debug"
HERE = os.path.dirname(os.path.abspath(__file__))
GECKODRIVER = os.path.join(HERE, "geckodriver.exe")


def log(*args):
    print(*args, flush=True)


def main():
    opts = Options()
    opts.headless = False  # visible so the user can watch
    opts.set_preference("devtools.console.stdout.content", True)
    svc = Service(executable_path=GECKODRIVER)
    driver = webdriver.Firefox(options=opts, service=svc)
    driver.set_window_size(480, 900)  # phone-ish
    logs = []

    try:
        log("== Opening PWA ==")
        driver.get(BASE)
        time.sleep(2)

        log("== Title ==", driver.title)

        # ---- Create a job ----
        log("== Clicking '+ New job' ==")
        driver.find_element(By.CSS_SELECTOR, '[data-action="newjob"]').click()
        time.sleep(1)

        # ---- Open the default Plan View sketch ----
        log("== Opening sketch ==")
        driver.find_element(By.CSS_SELECTOR, '[data-action="opensketch"]').click()
        time.sleep(1)

        # Check the sketch screen state
        body = driver.find_element(By.TAG_NAME, "body").text
        log("== Sketch screen contains photo prompt? ==", "Take or choose a photo" in body)

        # We need a photo for the canvas to exist. The app uses file input with
        # capture=environment; we can't easily supply a real photo, so instead
        # inject a synthetic photo via the app's own storage/shape.
        log("== Injecting synthetic photo via JS ==")
        driver.execute_script("""
            const T = window.__test;
            const job = T.state.jobs[0];
            const sk = job.sketches[0];
            // Build a tiny canvas-based JPEG data URL
            const c = document.createElement('canvas');
            c.width = 200; c.height = 150;
            const ctx = c.getContext('2d');
            ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,200,150);
            ctx.strokeStyle = '#333'; ctx.lineWidth = 4;
            ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(180,130); ctx.stroke();
            sk.photo = { dataUrl: c.toDataURL('image/jpeg', 0.8), width: 200, height: 150 };
            T.saveState();
        """)
        # Re-render sketch screen
        driver.execute_script("const T=window.__test; T.ui.screen='sketch'; T.ui.sketchId=T.state.jobs[0].sketches[0].id; T.render();")
        time.sleep(1)

        canvas = driver.find_element(By.ID, "sketchCanvas")
        log("== Canvas found ==", bool(canvas))

        # ---- Draw a line: pointer down, move, up ----
        log("== Drawing line on canvas ==")
        ac = ActionChains(driver)
        ac.move_to_element_with_offset(canvas, 40, 40)
        ac.click_and_hold()
        ac.move_by_offset(120, 80)
        ac.pause(0.3)
        ac.release()
        ac.perform()
        time.sleep(1)

        # ---- Check whether the modal opened ----
        overlay = driver.find_elements(By.CSS_SELECTOR, ".sheet-overlay")
        log("== Modal overlay present? ==", len(overlay) > 0)
        if overlay:
            sheet = driver.find_element(By.CSS_SELECTOR, ".sheet")
            log("== Sheet text ==", sheet.text[:300])

        # ---- Dump console logs ----
        time.sleep(0.5)
        log("== Console logs (from driver) ==")
        try:
            for entry in driver.get_log("browser"):
                logs.append(entry)
                log("  ", entry.get("level"), ":", entry.get("message"))
        except Exception as e:
            log("  (could not read browser log:", e, ")")

        # Also dump the app's own [DBG] logs by reading a global we set up.
        dbg = driver.execute_script("return window.__dbgLogs ? window.__dbgLogs.join('\\n') : '(none)'")
        log("== App [DBG] logs ==")
        log(dbg)

    finally:
        log("== Done ==")
        driver.quit()


if __name__ == "__main__":
    main()