#!/usr/bin/env python3
"""Compile production WSS callbacks/JSON dispatch and board disconnect on host.

Use the existing ESP-IDF cJSON source; no hardware, Speech playback or providers.
"""
import os
from pathlib import Path
import re
import subprocess
import tempfile

repo = Path(__file__).resolve().parents[2]
cloud = (repo/'firmware/main/cloud_client.cpp').read_text()
board = (repo/'boards/m5stack_stopwatch/board.cpp').read_text()

def functions(source, names):
    return '\n'.join(re.search(r'^[^\n]*\b'+name+r'\([^;]*?\)\s*\{.*?^}', source, re.M|re.S).group()
                     for name in names)

cjson = Path(os.environ.get('CJSON_DIR', repo/'.cache/esp-idf-v5.5.4/components/json/cJSON'))
with tempfile.TemporaryDirectory(prefix='network-resilience-') as folder:
    temp = Path(folder)
    (temp/'esp_err.h').write_text('typedef int esp_err_t;\n')
    (temp/'cloud.inc').write_text(functions(cloud, ('link_error_type', 'log_connection', 'mark_synchronized',
        'json_number', 'json_string', 'send_json', 'send_hello', 'handle_message', 'websocket_event', 'report_control_send_failure')))
    (temp/'history_response.inc').write_text(functions(board, ('history_message',)))
    (temp/'board_link.inc').write_text(functions(board, ('board_set_cloud_status', 'board_voice_interrupted', 'board_sync_utc_time')))
    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(repo/'boards/common/include'), '-I', str(repo/'firmware/main'), '-I', str(cjson),
        str(repo/'firmware/tests/network_resilience_test.cpp'), str(temp/'cjson.o'),
        '-o', str(temp/'test')], check=True)
    subprocess.run([str(temp/'test')], check=True)
