#!/usr/bin/env python3
from __future__ import annotations

import argparse
from pathlib import Path

from rt3_rekitlib import (
    PENDING_TEMPLATE_STORE_DEFAULT_SEEDS,
    export_pending_template_store,
    parse_hex,
)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="RT3 CLI RE kit for repeatable branch-deepening exports."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    pending = subparsers.add_parser(
        "pending-template-store",
        help="Export the pending-template dispatch-store dossier.",
    )
    pending.add_argument("exe_path", type=Path)
    pending.add_argument("output_dir", type=Path)
    pending.add_argument(
        "--seed-addr",
        action="append",
        default=[],
        help="Hex seed address. May be repeated.",
    )
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    if args.command == "pending-template-store":
        seed_addresses = (
            [parse_hex(value) for value in args.seed_addr]
            if args.seed_addr
            else list(PENDING_TEMPLATE_STORE_DEFAULT_SEEDS)
        )
        export_pending_template_store(
            args.exe_path.resolve(),
            args.output_dir.resolve(),
            seed_addresses,
        )
        return 0

    parser.error(f"unknown command: {args.command}")
    return 2


if __name__ == "__main__":
    raise SystemExit(main())
