#!/usr/bin/env python3
"""Compile the production modal/button arbiter and shell navigation on host."""
import os
from pathlib import Path
import re
import subprocess
import tempfile
repo=Path(__file__).resolve().parents[2]
source=(repo/'boards/m5stack_stopwatch/board.cpp').read_text()
names=('accept_voice_transcript','speech_mode_saved','open_speech_mode','open_double_session_picker',
       'history_request_page','history_rebuild_screen','open_agent_history','close_agent_history',
       'history_older','history_newer','history_message',
       'touch_note_contact_start','touch_virtual_click','touch_virtual_long_start','touch_virtual_long_end','touch_diagnostic',
       'agent_vertical_swipe','touch_gesture',
       'handle_gesture','poll_shell_button','board_next_page','board_previous_page')
cjson=Path(os.environ.get('CJSON_DIR',repo/'.cache/esp-idf-v5.5.4/components/json/cJSON'))
with tempfile.TemporaryDirectory(prefix='shell-input-') as folder:
    temp=Path(folder)
    text='\n'.join(re.search(r'^[^\n]*\b'+name+r'\([^;]*?\)\s*\{.*?^}',source,re.M|re.S).group() for name in names)
    (temp/'shell_input.inc').write_text(text)
    subprocess.run(['cc','-c',str(cjson/'cJSON.c'),'-I',str(cjson),'-o',str(temp/'cjson.o')],check=True)
    subprocess.run(['c++','-std=c++17','-Wall','-Wextra','-Werror','-I',str(temp),'-I',str(cjson),
        '-I',str(repo/'firmware/tests/nvs_stub'),'-I',str(repo/'boards/common/include'),
        str(repo/'firmware/tests/shell_input_test.cpp'),str(temp/'cjson.o'),'-o',str(temp/'test')],check=True)
    subprocess.run([str(temp/'test')],check=True)