"""Run the actual browser keyboard handler in Node with a minimal UI fixture.

No annotation DB is created. Browser tests separately exercise real keyboard
events, saved drafts and the full page; these cover boundary and guard cases.
"""
import shutil
import subprocess
from pathlib import Path

import pytest


PROJECT=Path(__file__).resolve().parents[1]
NODE=shutil.which('node') or '/tmp/opencode/pallet_review_browser_tools/node'
APP=PROJECT/'pallet/assets/pose_review/app.js'

FIXTURE=r'''
const assert=require('node:assert/strict');
const approx=(a,b)=>assert.ok(Math.abs(a-b)<1e-10,`${a} != ${b}`);
class Element { constructor(editable=false){this.editable=editable;} closest(){return this.editable;} }
const els={};
const $=id=>els[id]||(els[id]={hidden:id!=='app',open:false,disabled:false,value:'',click(){},showModal(){this.open=true},close(){this.open=false}});
$('dragAxes').value='x';
let edit={ruler:{w:.2,d:.1,angle:3,half_width:.5,direction_sign:-1,origin:[1,2,3],basis:[[0,1,0],[1,0,0],[0,0,1]]}};
let deleted=false,activePanel='cloud',navigating=false,imageDrag=null,cloudDrag=null,index=0,draftRecoveryError=false;
let dirty=false,poseConfirmed=true,changes=0,unitFactor=1000,undo=[],redo=[];
let view={span:2,centerW:.2,centerD:.1,centerH:0},cloudDraws=0;
const drawCloud=()=>{cloudDraws++};
const document={body:{classList:{contains:()=>false}},querySelector:()=>({click(){}})};
const isDeleted=()=>deleted;
const factor=()=>unitFactor;
const positionStep=()=>.001;
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const checkpoint=()=>{undo.push(structuredClone(edit.ruler));redo=[]};
const poseChanged=()=>{dirty=true;poseConfirmed=false;changes++};
const state=()=>JSON.stringify(edit.ruler);
function press(letter,extra={}){
 const event={key:letter,code:'Key'+letter.toUpperCase(),altKey:true,shiftKey:false,ctrlKey:false,metaKey:false,
  defaultPrevented:false,isComposing:false,keyCode:0,repeat:false,target:null,
  getModifierState(){return false},preventDefault(){this.defaultPrevented=true},...extra};
 keyboardShortcut(event);return event.defaultPrevented;
}
'''

CASES={
    'total_width_and_rotation_not_translation':r'''
      const original=structuredClone(edit.ruler);
      assert.equal(press('h'),true);approx(edit.ruler.half_width,.4995);
      approx(edit.ruler.w,original.w);approx(edit.ruler.d,original.d);approx(edit.ruler.angle,original.angle);
      assert.equal(press('l'),true);approx(edit.ruler.half_width,original.half_width);
      assert.equal(press('j'),true);approx(edit.ruler.angle,original.angle-.1);
      assert.equal(press('k'),true);approx(edit.ruler.angle,original.angle);
      assert.deepEqual(edit.ruler,original);assert.equal(changes,4);
      assert.equal(dirty,true);assert.equal(poseConfirmed,false);assert.equal(undo.length,4);
    ''',
    'shift_and_held_repeat':r'''
      press('l',{shiftKey:true});approx(edit.ruler.half_width,.505);
      press('h',{shiftKey:true});approx(edit.ruler.half_width,.5);
      press('j',{shiftKey:true});approx(edit.ruler.angle,2);
      press('k',{shiftKey:true});approx(edit.ruler.angle,3);
      press('l',{repeat:true});press('l',{repeat:true});approx(edit.ruler.half_width,.501);
      assert.equal(undo.length,6);
    ''',
    'total_width_step_is_always_0point001_metres':r'''
      for(const f of [1000,100,1]){
       unitFactor=f;edit.ruler.half_width=2;
       press('l');approx(edit.ruler.half_width,2+.001/2);
       press('h');approx(edit.ruler.half_width,2);
      }
    ''',
    'width_positive_minimum_and_angle_validity':r'''
      for(const f of [1000,100,1]){
       unitFactor=f;edit.ruler.half_width=.0006/f;
       press('h',{shiftKey:true});approx(edit.ruler.half_width,.000001/2);
       const n=changes;press('h');assert.equal(changes,n);
       assert.ok(Number.isFinite(edit.ruler.half_width)&&edit.ruler.half_width>0);
      }
      edit.ruler.angle=35999.99;press('k',{shiftKey:true});assert.equal(edit.ruler.angle,36000);
      let n=changes;press('k');assert.equal(changes,n);
      edit.ruler.angle=-35999.99;press('j',{shiftKey:true});assert.equal(edit.ruler.angle,-36000);
    ''',
    'width_angle_ignore_xy_translation_lock':r'''
      for(const axes of ['x','y','xy']){
       $('dragAxes').value=axes;const before=structuredClone(edit.ruler);
       press('l');press('k');approx(edit.ruler.w,before.w);approx(edit.ruler.d,before.d);
       approx(edit.ruler.half_width,before.half_width+.0005);approx(edit.ruler.angle,before.angle+.1);
      }
    ''',
    'inputs_modals_deleted_loading_and_empty_queue':r'''
      const before=state();
      for(const id of ['jumpDialog','objectDialog','shortcuts']){
       $(id).open=true;for(const k of 'hjkl')assert.equal(press(k),false);$(id).open=false;
      }
      for(const k of 'hjkl')assert.equal(press(k,{target:new Element(true)}),false);
      deleted=true;press('l');deleted=false;
      index=-1;press('l');index=0;
      activePanel='image';press('l');activePanel='cloud';
      navigating=true;press('l');navigating=false;
      imageDrag={};press('l');imageDrag=null;cloudDrag={};press('l');cloudDrag=null;
      document.body.classList.contains=()=>true;press('l');document.body.classList.contains=()=>false;
      assert.equal(state(),before);assert.equal(changes,0);assert.equal(dirty,false);
    ''',
    'IME_AltGraph_unrelated_Alt_and_other_modifiers':r'''
      const before=state();
      for(const extra of [{ctrlKey:true},{metaKey:true},{isComposing:true},{keyCode:229},
       {defaultPrevented:true},{getModifierState:name=>name==='AltGraph'}])press('l',extra);
       for(const k of ['s','r','g','?','Escape'])assert.equal(press(k),false);
       assert.equal(state(),before);assert.equal(changes,0);
    ''',
    'Option_alternate_character_and_original_HJKL':r'''
      press('¬',{code:'KeyL'});approx(edit.ruler.half_width,.5005);
      press('h',{altKey:false});approx(edit.ruler.w,.199);
      press('l',{altKey:false});approx(edit.ruler.w,.2);
      press('j',{altKey:false});approx(edit.ruler.d,.1);
      $('dragAxes').value='xy';press('k',{altKey:false});approx(edit.ruler.d,.101);
       assert.equal($('shortcuts').open,false);
    ''',
    'Alt_A_D_zoom_only_shared_view_without_edits':r'''
      const original=state(),oldView=structuredClone(view);
      assert.equal(press('a'),true);approx(view.span,2*1.3);
      assert.equal(press('d'),true);approx(view.span,2);
      press('d',{repeat:true});press('d',{repeat:true});approx(view.span,2/1.3/1.3);
      assert.equal(state(),original);assert.equal(dirty,false);assert.equal(poseConfirmed,true);
      assert.equal(changes,0);assert.equal(undo.length,0);assert.equal(cloudDraws,4);
      for(const k of ['centerW','centerD','centerH'])assert.equal(view[k],oldView[k]);
      press('∂',{code:'KeyD'});approx(view.span,2/1.3/1.3/1.3);
    ''',
    'Alt_zoom_boundaries_and_inactive_contexts':r'''
      view.span=1e-8;press('d');assert.equal(view.span,1e-8);
      view.span=1e8;press('a');assert.equal(view.span,1e8);
      view.span=2;
      for(const id of ['jumpDialog','objectDialog','shortcuts']){
       $(id).open=true;for(const k of 'ad')assert.equal(press(k),false);$(id).open=false;
      }
      for(const k of 'ad'){
       assert.equal(press(k,{target:new Element(true)}),false);
       for(const extra of [{ctrlKey:true},{metaKey:true},{isComposing:true},{keyCode:229},
        {defaultPrevented:true},{getModifierState:name=>name==='AltGraph'}])assert.equal(press(k,extra),!!extra.defaultPrevented);
      }
      deleted=true;press('d');deleted=false;
      index=-1;press('d');index=0;
      activePanel='image';press('d');activePanel='cloud';
      navigating=true;press('d');navigating=false;
      imageDrag={};press('d');imageDrag=null;cloudDrag={};press('d');cloudDrag=null;
      document.body.classList.contains=()=>true;press('d');document.body.classList.contains=()=>false;
      assert.equal(view.span,2);assert.equal(dirty,false);assert.equal(changes,0);
    ''',
}


@pytest.mark.parametrize('scenario',CASES)
def test_actual_keyboard_handler(scenario):
    if not Path(NODE).is_file():pytest.skip('Node required for browser handler unit tests')
    source=APP.read_text();handler=source[source.index('function zoomCloud(multiplier)'):source.index('\nfunction wire()')]
    completed=subprocess.run([NODE,'-e',FIXTURE+'\n'+handler+'\n'+CASES[scenario]],text=True,capture_output=True,timeout=15)
    assert completed.returncode==0,completed.stdout+'\n'+completed.stderr
