#!/usr/bin/env python3
"""Run actual board render functions against a recording display, without ESP-IDF.

Only hardware/font rasterization is substituted. The production text selection,
wrapping, redraw comparison and Read Screen code are compiled unchanged.
"""
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 = ('utf8_boundary', 'set_pi_tail', 'append_pi_tail', 'utf8_character_size', 'wrap_activity_text',
         'stored_text_equal', 'rendered_tail_equal', 'pi_snapshot_changes_view', 'read_screen_text', 'draw_pi',
         'board_append_pi_activity', 'board_agent_activity')
pieces = []
for name in names:
    # These top-level functions end with an unindented closing brace.
    match = re.search(r'^(?:template[^\n]*\n)?[^\n]*\b' + name + r'\([^;\n]*\)\s*\{.*?^}', source, re.M | re.S)
    if not match:
        raise AssertionError(f'production function not found: {name}')
    pieces.append(match.group())
state = re.search(r'^struct PiState \{.*?^};', source, re.M | re.S).group()
with tempfile.TemporaryDirectory(prefix='agent-view-') as folder:
    root = Path(folder)
    (root/'esp_err.h').write_text('typedef int esp_err_t;\n')
    (root/'agent_state.inc').write_text(state)
    (root/'agent_view.inc').write_text('\n'.join(pieces))
    command = ['c++', '-std=c++17', '-Wall', '-Wextra', '-Werror', '-I', str(root),
               '-I', str(repo/'boards/common/include'), str(repo/'firmware/tests/agent_view_test.cpp'),
               '-o', str(root/'test')]
    if 'const char *final_text;' in (repo/'boards/common/include/board.h').read_text():
        command.insert(1, '-DHAS_FINAL_TEXT')
    subprocess.run(command, check=True)
    subprocess.run([str(root/'test')], check=True)
