from __future__ import annotations

import argparse
import json
import sys

from .v2 import TxIdV2Generator, parse_txid_v2


def _cmd_gen(args: argparse.Namespace) -> int:
    gen = TxIdV2Generator(node_id=args.node)
    txid = gen.generate(prefix=args.prefix, currency=args.currency)
    print(txid)
    return 0


def _cmd_parse(args: argparse.Namespace) -> int:
    parts = parse_txid_v2(args.txid)
    out = {
        "prefix": parts.prefix,
        "ts10": parts.ts10,
        "node": parts.node,
        "currency_id": parts.currency_id,
        "currency": parts.currency,
        "seq": parts.seq,
        "unix_seconds": parts.unix_seconds,
        "unix_ns_approx": parts.unix_ns_approx,
    }
    print(json.dumps(out, indent=2))
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="txidgen", description="Generate/parse human-safe sortable TxIDs.")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_gen = sub.add_parser("gen", help="Generate a V2 TxID")
    p_gen.add_argument("--prefix", required=True, help="Single letter prefix (e.g. P, D)")
    p_gen.add_argument("--currency", required=True, help="Currency code (e.g. BDT)")
    p_gen.add_argument("--node", required=True, type=int, help="Node id 0..15")
    p_gen.set_defaults(fn=_cmd_gen)

    p_parse = sub.add_parser("parse", help="Parse a V2 TxID")
    p_parse.add_argument("txid", help="TxID to parse (12 chars)")
    p_parse.set_defaults(fn=_cmd_parse)

    args = parser.parse_args(argv)
    return int(args.fn(args))


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
