"""Generate the actual ArUco board images that match the CAD pockets (the printable half
of the fidex coupling), from fidex_config.json. DICT_4X4_250.
Marker:separation = 0.8:0.2 (medium_single_redo). Output: fidex_markers/<link>.png at ~12 px/mm.
"""
import json
import os
import numpy as np
import cv2

cfg = json.load(open("/data/cameron/repos/smith300_para_stuff/fidex_config.json"))
os.makedirs("/data/cameron/repos/smith300_para_stuff/fidex_markers", exist_ok=True)
dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)

for c in cfg:
    gx, gy = c["grid"]
    n = gx * gy
    ids = c["ids"]
    if len(ids) < n:
        ids = list(range(ids[0], ids[0] + n))      # expand to a full sequential block
    B = c["board_length"]
    unit_span = gx * 0.8 + (gx - 1) * 0.2
    mlen = 0.8 * B / unit_span
    sep = 0.2 * B / unit_span
    board = cv2.aruco.GridBoard((gx, gy), mlen, sep, dictionary, np.array(ids, dtype=np.int32))
    px = max(240, int(round(B * 1000 * 12)))        # ~12 px/mm
    img = board.generateImage((px, px), marginSize=int(px * 0.05), borderBits=1)
    out = f"/data/cameron/repos/smith300_para_stuff/fidex_markers/{c['link']}.png"
    cv2.imwrite(out, img)
    print(f"{c['link']}: {gx}x{gy} ids {ids[0]}-{ids[-1]} board {B*1000:.0f}mm -> {px}px {out.split('/')[-1]}")
