import os, sys, time
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

HERE = os.path.dirname(os.path.abspath(__file__))
GECKODRIVER = os.path.join(HERE, "geckodriver.exe")
BASE = "http://localhost:8000/field-capture.html?debug"

opts = Options()
opts.headless = False
svc = Service(executable_path=GECKODRIVER)
d = webdriver.Firefox(options=opts, service=svc)
d.set_window_size(480, 900)

d.get(BASE + "&_=" + str(int(time.time())))
time.sleep(2)
d.find_element(By.CSS_SELECTOR, '[data-action="newjob"]').click()
time.sleep(0.5)
d.find_element(By.CSS_SELECTOR, '[data-action="opensketch"]').click()
time.sleep(0.5)
d.execute_script("""
    const T = window.__test;
    const job = T.state.jobs[0];
    const sk = job.sketches[0];
    const c = document.createElement('canvas');
    c.width = 400; c.height = 300;
    const ctx = c.getContext('2d');
    ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,400,300);
    sk.photo = { dataUrl: c.toDataURL('image/jpeg', 0.8), width: 400, height: 300 };
    T.saveState();
""")
d.execute_script("const T=window.__test; T.ui.screen='sketch'; T.ui.sketchId=T.state.jobs[0].sketches[0].id; T.render();")
time.sleep(0.5)

# Try the same DRAW_JS as in the test
DRAW_JS = """
(function(){
  const canvas = document.getElementById('sketchCanvas');
  canvas.setPointerCapture = function(){};
  canvas.releasePointerCapture = function(){};
  canvas.hasPointerCapture = function(){ return false; };
  const rect = canvas.getBoundingClientRect();
  const opts = { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true };
  const sx = rect.left + rect.width*0.3, sy = rect.top + rect.height*0.4;
  const ex = rect.left + rect.width*0.7, ey = rect.top + rect.height*0.6;
  canvas.dispatchEvent(new PointerEvent('pointerdown', Object.assign({}, opts, {clientX: sx, clientY: sy})));
  for (let i = 1; i <= 5; i++) canvas.dispatchEvent(new PointerEvent('pointermove', Object.assign({}, opts, {clientX: sx+(ex-sx)*i/5, clientY: sy+(ey-sy)*i/5})));
  canvas.dispatchEvent(new PointerEvent('pointerup', Object.assign({}, opts, {clientX: ex, clientY: ey})));
  return 'drawn';
})();
"""

print("DRAW_JS result:", repr(d.execute_script(DRAW_JS)))
time.sleep(0.5)
print("line count:", d.execute_script("return window.__test.state.jobs[0].sketches[0].lines.length"))

# Now try setLineValue
print("setLineValue result:", d.execute_script("""
const T = window.__test;
const sk = T.state.jobs[0].sketches[0];
const line = sk.lines[0];
console.log('line before:', JSON.stringify(line));
T.setLineValue(line, { feet: 8, inches: 4, sixteenths: 2 });
T.saveState();
console.log('line after:', JSON.stringify(line));
return JSON.stringify(line);
"""))
d.quit()