#!/usr/bin/env python3
"""Run the test_apps Unity tests in Espressif's QEMU and report the result.

Usage (from an ESP-IDF shell, after ``idf.py set-target esp32 build``):

    python run_qemu.py [--build-dir build] [--tests '![littlefs_benchmark]']

The script merges the build into a 4MB flash image, boots it in
``qemu-system-xtensa``, drives the Unity menu and exits non-zero when a test
fails, the firmware crashes, or the run times out.
"""

import argparse
import os
import re
import select
import shutil
import subprocess
import sys
import tempfile
import time

SUMMARY = re.compile(rb"(\d+) Tests (\d+) Failures (\d+) Ignored")
CRASH = re.compile(rb"Guru Meditation Error|abort\(\) was called|Rebooting\.\.\.")


def log(msg):
    """Report a runner decision, on its own line amid the firmware output."""
    print(f"\n[run_qemu] {msg}", file=sys.stderr, flush=True)


def merge_flash(build_dir, image):
    subprocess.run(
        [sys.executable, "-m", "esptool", "--chip", "esp32", "merge-bin",
         "--fill-flash-size", "4MB", "-o", image, "@flash_args"],
        cwd=build_dir, check=True, stdout=subprocess.DEVNULL,
    )


def run(qemu, image, tests, timeout):
    proc = subprocess.Popen(
        [qemu, "-nographic", "-machine", "esp32", "-m", "4M",
         "-drive", f"file={image},if=mtd,format=raw", "-nic", "none"],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
    )
    os.set_blocking(proc.stdout.fileno(), False)
    buf = b""
    state = "boot"
    start = time.monotonic()
    last_enter = 0.0
    selection = tests.encode() + b"\n"
    sent_pos = sent_at = run_pos = attempts = 0
    try:
        while time.monotonic() - start < timeout:
            ready, _, _ = select.select([proc.stdout], [], [], 1)
            if ready:
                data = proc.stdout.read() or b""
                if not data and proc.poll() is not None:
                    log("QEMU exited unexpectedly")
                    return 1
                sys.stdout.buffer.write(data)
                sys.stdout.flush()
                buf += data
            if CRASH.search(buf):
                log("firmware crashed")
                return 1
            if state == "boot" and b"Press ENTER" in buf:
                state = "menu"
            if state == "menu" and b"Enter test for running" not in buf:
                # The prompt prints before the UART is read, so a single early
                # Enter can be lost. Resend it until the menu shows up.
                if time.monotonic() - last_enter > 1:
                    proc.stdin.write(b"\n")
                    proc.stdin.flush()
                    last_enter = time.monotonic()
            elif state == "menu" and buf.endswith(b"\n"):
                # Send only once the prompt line has fully arrived, or its tail
                # gets mistaken for the echo. unity_gets() flushes the RX buffer before reading, so the
                # selection can be dropped (wholly or in part) if it lands
                # before that flush. Unity echoes what it reads; wait for the
                # full selection to come back before trusting the run.
                attempts += 1
                log(f"sending selection {tests!r} (attempt {attempts})")
                proc.stdin.write(selection)
                proc.stdin.flush()
                sent_pos = len(buf)
                sent_at = time.monotonic()
                state = "selecting"
            elif state == "selecting":
                # Skip any blank line left over from the prompt.
                reply = buf[sent_pos:].lstrip(b"\r\n")
                line_end = reply.find(b"\n")
                if line_end >= 0:
                    if reply[:line_end].strip() == selection.strip():
                        log("selection acknowledged")
                        state = "running"
                        run_pos = len(buf) - len(reply) + line_end
                    else:
                        # Only a tail of the selection was read; let that
                        # command finish, then send the selection again.
                        log(f"only part of the selection was read ({reply[:line_end].strip()!r}); "
                            "resending after it finishes")
                        state = "garbled"
                elif not reply and time.monotonic() - sent_at > 3:
                    # Nothing echoed: the whole selection was flushed.
                    log("no echo after 3s; resending selection")
                    state = "menu"
            elif state == "garbled":
                # A bare newline reprints the menu; anything else runs as a
                # command and ends with "Enter next test".
                after = buf[sent_pos:]
                if b"Enter next test" in after or b"Enter test for running" in after:
                    state = "menu"
            elif state == "running":
                match = SUMMARY.search(buf, run_pos)
                if match:
                    tests_run, failures = int(match.group(1)), int(match.group(2))
                    log(f"{tests_run} tests ran, {failures} failed")
                    if tests_run == 0:
                        log(f"no tests matched {tests!r}")
                        return 1
                    return 0 if failures == 0 else 1
        log(f"timed out after {timeout}s (state: {state})")
        return 1
    finally:
        proc.kill()
        proc.wait()


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--build-dir", default="build")
    parser.add_argument("--tests", default="![littlefs_benchmark]",
                        help="Unity menu input: '*', a test number, '[tag]' or '![tag]'")
    parser.add_argument("--timeout", type=float, default=3000, help="seconds")
    parser.add_argument("--qemu", default=shutil.which("qemu-system-xtensa"))
    args = parser.parse_args()

    if not args.qemu:
        sys.exit("qemu-system-xtensa not found; run `idf_tools.py install qemu-xtensa` "
                 "and re-export the ESP-IDF environment")

    with tempfile.TemporaryDirectory() as tmp:
        image = os.path.join(tmp, "flash.bin")
        merge_flash(os.path.abspath(args.build_dir), image)
        sys.exit(run(args.qemu, image, args.tests, args.timeout))


if __name__ == "__main__":
    main()
