#!/usr/bin/env python3
"""Run actual GPIO sampler and queue consumer with deterministic RTOS scheduling."""
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 = ("publish_button_policy", "button_sample_task", "consume_button_events")
with tempfile.TemporaryDirectory(prefix="button-sampler-") as folder:
    temp = Path(folder)
    functions = []
    for name in names:
        match = re.search(r"^[^\n]*\b" + name + r"\([^;]*?\)\s*\{.*?^}", source, re.M | re.S)
        if match is None:
            raise AssertionError("Missing production function: " + name)
        functions.append(match.group())
    (temp / "button_sampler.inc").write_text("\n".join(functions))
    subprocess.run(["c++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
                    "-I", str(temp), "-I", str(repo / "boards/common/include"),
                    str(repo / "firmware/tests/button_sampler_test.cpp"),
                    "-o", str(temp / "test")], check=True)
    subprocess.run([str(temp / "test")], check=True)
