#!/usr/bin/env python3
"""Exercise actual device Navigator reducers and JSON handlers with host cJSON."""
from pathlib import Path
import re,subprocess,tempfile
repo=Path(__file__).resolve().parents[2]
source=(repo/'boards/m5stack_stopwatch/board.cpp').read_text()
names=('navigator_command','navigator_busy','navigator_catalog','openAgentSessionPicker','navigator_models','navigator_efforts','navigator_permissions','load_permissions','native_approval_response','navigator_voice','navigator_gesture','navigator_message','board_accept_target')
def extract(name):
 match=re.search(r'^[^\n]*\b'+name+r'\([^;]*?\)\s*\{',source,re.M|re.S)
 start=match.start();i=match.end()-1;depth=0;quote=None
 while i<len(source):
  char=source[i]
  if quote:
   if char=='\\':i+=2;continue
   if char==quote:quote=None
  elif char in ('"',"'"):quote=char
  elif source[i:i+2]=='//':i=source.index('\n',i);continue
  elif source[i:i+2]=='/*':i=source.index('*/',i)+2;continue
  elif char=='{':depth+=1
  elif char=='}':
   depth-=1
   if depth==0:return source[start:i+1]
  i+=1
 raise RuntimeError(name)
with tempfile.TemporaryDirectory(prefix='navigator-input-') as folder:
 temp=Path(folder)
 (temp/'navigator_input.inc').write_text('\n'.join(extract(n) for n in names))
 cjson=repo/'.cache/esp-idf-v5.5.4/components/json/cJSON'
 subprocess.run(['cc','-c','-I',str(cjson),str(cjson/'cJSON.c'),'-o',str(temp/'json.o')],check=True)
 subprocess.run(['c++','-std=c++17','-Wall','-Wextra','-Werror','-I',str(temp),'-I',str(cjson),'-I',str(repo/'boards/common/include'),str(repo/'firmware/tests/navigator_input_test.cpp'),str(temp/'json.o'),'-o',str(temp/'test')],check=True)
 subprocess.run([str(temp/'test')],check=True)
