#!/usr/bin/env python3
import argparse
from pathlib import Path

from hil_common import HilError, load_config, main_guard, new_artifact_dir, pair_ports, pio_command, run_checked


def flash_pair(artifact: Path, yes_flash: bool) -> None:
    if not yes_flash:
        raise HilError("refusing to flash without --yes-flash")
    config = load_config()
    ports = pair_ports(config, "flash")
    environment = config.get("hil", {}).get("environment", "hil")
    artifact.mkdir(parents=True, exist_ok=True)
    run_checked([pio_command(), "run", "-e", environment], log=artifact / "build.log")
    for port in ports:
        run_checked([pio_command(), "run", "-e", environment, "-t", "upload", "--upload-port", str(port.device)],
                    log=artifact / f"flash-{port.name}.log")


def main() -> int:
    parser = argparse.ArgumentParser(description="Build once and flash the explicitly approved board pair")
    parser.add_argument("--yes-flash", action="store_true", help="confirm the approved_flash entries for this invocation")
    parser.add_argument("--artifact-dir")
    args = parser.parse_args()
    artifact = Path(args.artifact_dir) if args.artifact_dir else new_artifact_dir("flash")
    flash_pair(artifact, args.yes_flash)
    print(f"Flash logs: {artifact}")
    return 0


if __name__ == "__main__":
    main_guard(main)
