# Referencia Python del DIBUJO de maniobras de izaje (man_figuras, man_fig_trayectoria, man_transformar, man3d_escena, man_ubicar).
# Arma miles de casos variados, calcula res = man_calcular(d) en Python y guarda lo que dibuja Python, un caso por línea (JSONL).
# Uso: python tests/js/ref_figuras.py [N=3200] [semilla=91] [salida=storage/app/paridad/_ref_figuras.jsonl]
import io, json, math, os, random, sys

AQUI = os.path.dirname(os.path.abspath(__file__))
TMS_DIR = os.path.abspath(os.path.join(AQUI, "..", "..", ".."))          # 00_Aplicativo
sys.path.insert(0, TMS_DIR)
_o = sys.stdout; sys.stdout = io.StringIO()
try:
    import toolroom_management_system as T
finally:
    sys.stdout = _o

N = int(sys.argv[1]) if len(sys.argv) > 1 else 3200
SEM = int(sys.argv[2]) if len(sys.argv) > 2 else 91
SALIDA = sys.argv[3] if len(sys.argv) > 3 else os.path.join(AQUI, "..", "..", "storage", "app", "paridad", "_ref_figuras.jsonl")
os.makedirs(os.path.dirname(os.path.abspath(SALIDA)), exist_ok=True)
rnd = random.Random(SEM)


def limpio(o):
    """tuplas -> listas, conjuntos -> listas ordenadas, nan/inf -> {"__f": "..."} (JSON estricto)."""
    if isinstance(o, float):
        if math.isnan(o): return {"__f": "nan"}
        if math.isinf(o): return {"__f": "inf" if o > 0 else "-inf"}
        return o
    if isinstance(o, (list, tuple)): return [limpio(x) for x in o]
    if isinstance(o, (set, frozenset)): return [limpio(x) for x in sorted(o)]
    if isinstance(o, dict): return {str(k): limpio(v) for k, v in o.items()}
    if o is None or isinstance(o, (bool, int, str)): return o
    return str(o)


def err(e):
    return {"__error": type(e).__name__, "msg": str(e)[:200]}


def num(a, b, nd=2):
    return round(rnd.uniform(a, b), nd)


def medida(a, b):
    r = rnd.random()
    if r < 0.03: return None
    if r < 0.06: return str(num(a, b)).replace(".", ",")          # "2,5" como lo escribe la gente
    if r < 0.08: return ""
    return num(a, b, rnd.choice([1, 2, 3]))


def caso(k):
    d = T.man_por_defecto()
    forma = rnd.choice(T.MAN_FORMAS + T.MAN_FORMAS + [T.MAN_FORMA_BIGBAG])
    d["forma"] = forma
    d["tipo_carga"] = "Big bags" if rnd.random() < 0.18 else rnd.choice([t[0] for t in T.MAN_TIPOS_CARGA])
    L, A, H = num(0.4, 12), num(0.3, 6), num(0.3, 6)
    if rnd.random() < 0.15: L, A, H = num(0.05, 1.2), num(0.05, 1.2), num(0.05, 1.2)
    d["L"], d["A"], d["H"] = L, A, H
    if rnd.random() < 0.08: d["L"] = medida(0.4, 12)
    if rnd.random() < 0.08: d["H"] = medida(0.3, 6)
    d["base_piso"] = 0.0 if rnd.random() < 0.6 else num(0.05, 2.0)
    pl = rnd.choice(T.MAN_PLANTILLAS); d["plantilla"] = pl
    Lf, Af, Hf = T._man_f(d["L"], 1.0) or 1.0, T._man_f(d["A"], 1.0) or 1.0, T._man_f(d["H"], 1.0) or 1.0
    pts = T.man_plantilla(pl, Lf, Af, Hf, forma if forma in T.MAN_FORMAS else T.MAN_FORMAS[0])
    r = rnd.random()
    if r < 0.25:
        for p in pts: p["x"] = round(p["x"] + rnd.uniform(-0.3, 0.3), 3); p["y"] = round(p["y"] + rnd.uniform(-0.2, 0.2), 3)
    elif r < 0.32:
        pts = pts + [dict(pts[0])]                              # dos puntos en el mismo lugar (se agrupan)
    elif r < 0.37:
        pts = [{"x": num(0, Lf), "y": num(0, Af), "z": rnd.choice([0.0, Hf, num(0, Hf)])} for _ in range(rnd.randint(1, 8))]
    elif r < 0.40:
        pts = []
    d["puntos"] = pts
    d["cg"] = {"x": round(Lf / 2 + rnd.uniform(-0.3, 0.3) * Lf * (rnd.random() < 0.5), 3), "y": round(Af / 2 + rnd.uniform(-0.2, 0.2) * Af * (rnd.random() < 0.3), 3),
               "z": round(Hf * rnd.uniform(0.2, 0.7), 3)}
    if forma == "Pieza irregular" or rnd.random() < 0.05:
        c = T.man_contorno_inicial(Lf, Af)
        r = rnd.random()
        if r < 0.6: c = [[round(x + rnd.uniform(-0.2, 0.2), 3), round(y + rnd.uniform(-0.2, 0.2), 3)] for x, y in c]
        elif r < 0.7: c = c[:2]
        elif r < 0.75: c = []
        d["contorno"] = c
    d["peso"] = rnd.choice([num(0.1, 60), num(0.1, 5), 0.0 if rnd.random() < 0.05 else num(1, 20)])
    d["exterior"] = rnd.choice(T.MAN_EXTERIOR + ["", "Vidrio"])
    d["pintura"] = rnd.choice(T.MAN_PINTURA)
    d["interior_mov"] = rnd.random() < 0.2; d["rebabas"] = rnd.random() < 0.2; d["girar"] = rnd.random() < 0.2; d["borde_3m"] = rnd.random() < 0.2
    d["fragil"] = rnd.choice(T.MAN_FRAGIL)
    if rnd.random() < 0.05: del d["fragil"]
    d["ciclos"] = rnd.choice([1, 1, 2, 3, 10, "4", 0])
    d["nivel"] = rnd.choice(T.MAN_NIVEL); d["dif_nivel"] = rnd.choice([0.0, num(0.1, 3), num(3, 20)])
    d["grua_puntos"] = rnd.choice([1, 1, 2, "2"]); d["grua_sep"] = rnd.choice([0.0, num(0.5, 6)])
    d["desv_gancho"] = rnd.choice([0.0, 0.0, num(-1.5, 1.5)])
    d["adyacentes"] = rnd.random() < 0.25; d["dist_ady"] = rnd.choice([0.0, num(0.2, 4)])
    d["h_disp"] = rnd.choice([0.0, num(0.5, 12), 6.0])
    d["igualador"] = rnd.random() < 0.15; d["rigida"] = rnd.random() < 0.8
    d["sujecion"] = rnd.choice(T.MAN_SUJECION)
    if rnd.random() < 0.25:
        d["con_puntos"] = False
        d["metodo_sp"] = rnd.choice(T.MAN_METODOS_SP); d["acc_esp"] = rnd.choice([""] + list(T.MAN_ACC))
        d["amarre"] = rnd.choice([a[0] for a in T.MAN_AMARRES])
    if rnd.random() < 0.28:
        d["usar_sep"] = True
        if rnd.random() < 0.8:
            d["niveles"] = [dict(T.man_nivel_vacio(), n=rnd.choice([1, 1, 2]), tipo=rnd.choice(T.MAN_SEP_TIPOS), cap=rnd.choice([0.0, num(2, 60)]),
                                 peso=num(0, 1.5), largo=rnd.choice([0.0, num(0.5, 12)]), ancho=rnd.choice([0.0, num(0.3, 4)]),
                                 bajo=rnd.choice([1, 2, 3, 4, 6]), sobre=rnd.choice([1, 2, 4]), dist=rnd.choice([0.0, num(0.3, 3)]))
                            for _ in range(rnd.randint(1, 3))]
        else:
            d["sep_tipo"] = rnd.choice(T.MAN_SEP_TIPOS); d["sep_largo"] = num(1, 10); d["sep_cap"] = num(2, 40); d["sep_peso"] = num(0, 1)
    d["grua_tipo"] = rnd.choice(T.MAN_GRUAS + [None, "Otra grúa"])
    d["radio"] = rnd.choice([0.0, num(2, 40)]); d["h_boom"] = rnd.choice([0.0, num(4, 50)])
    d["cap_grua"] = rnd.choice([0.0, num(5, 100)]); d["cap_h_ext"] = rnd.choice([0.0, num(5, 100)]); d["cap_r_ext"] = rnd.choice([0.0, num(5, 100)])
    if rnd.random() < 0.35:
        n = rnd.randint(1, 6); x = num(-5, 10)
        tr = []
        for _ in range(n):
            tr.append([x, rnd.choice([0.0, num(0, 12)])]); x = round(x + rnd.uniform(-2, 8), 2)
        if rnd.random() < 0.1: tr.append(["x", 2])                 # punto malo: se descarta
        d["trayectoria"] = tr
    if rnd.random() < 0.3:
        d["obst_tray"] = [{"nom": rnd.choice(["", "Muro", "Contenedor %d" % i]), "x0": num(-5, 20), "x1": num(-5, 20), "h": num(0, 10)} for i in range(rnd.randint(1, 4))]
    if rnd.random() < 0.3:
        t = {"ini": [num(-15, 15), num(-15, 15)], "fin": [num(-25, 25), num(-25, 25)] if rnd.random() < 0.9 else None,
             "via": [[num(-20, 20), num(-20, 20)] for _ in range(rnd.choice([0, 0, 1, 2, 3]))], "alto": rnd.choice([0.0, 0.0, num(1, 15)])}
        if rnd.random() < 0.05: t["ini"] = None
        d["tray3d"] = t
    if rnd.random() < 0.35:
        d["obst3d"] = []
        for i in range(rnd.randint(1, 5)):
            tp = rnd.choice(T.MAN_OBST_TIPOS)
            o = {"nom": rnd.choice(["", tp[2], "Obs %d" % i]), "tipo": tp[0], "x": num(-20, 20), "y": num(-20, 20)}
            if rnd.random() < 0.6: o.update(l=num(0.3, 10), a=num(0.3, 5), h=num(0.2, 9))
            d["obst3d"].append(o)
    return d


def figs(d, res, vista):
    try: return limpio(T.man_figuras(d, res, vista))
    except Exception as e: return err(e)


cont = {"casos": 0, "res_error": 0, "separadores_aparejo": 0, "usar_sep": 0, "tray3d": 0, "obst3d": 0, "escena3d": 0, "pieza_irregular_contorno": 0,
        "portico": 0, "pluma": 0, "big_bag": 0, "sin_puntos": 0, "accesorio_sp": 0, "grua_2_puntos": 0, "desv_gancho": 0, "adyacentes": 0, "borde_3m": 0,
        "girar": 0, "rebabas": 0, "pintura_especial": 0, "ciclica": 0, "h_disp": 0, "nivel_distinto": 0, "trayectoria_2d": 0, "obst_tray": 0,
        "con_pendulo": 0, "fig_error": 0}

with open(SALIDA, "w", encoding="utf-8") as fh:
    for k in range(N):
        d = json.loads(json.dumps(caso(k)))                     # lo mismo que recibe JS
        try: res = T.man_calcular(json.loads(json.dumps(d)))
        except Exception as e: res = None; cont["res_error"] += 1
        res_j = json.loads(json.dumps(limpio(res))) if res is not None else None
        out = {"k": k, "d": d, "res": res_j, "fig": {}, "tr": {}}
        for v in ("arriba", "frente", "costado", "trayectoria"):
            try: F = T.man_figuras(d, res, v); out["fig"][v] = limpio(F)
            except Exception as e: out["fig"][v] = err(e); F = None; cont["fig_error"] += 1
            if F is not None:
                aw, ah = rnd.choice([(800, 500), (640, 420), (1200, 700)])
                m2p, p2m = T.man_transformar(F, aw, ah)
                mp = [(0.0, 0.0), (1.5, -2.25), (rnd.uniform(-10, 10), rnd.uniform(-10, 10))]
                pp = [(0.0, 0.0), (400.0, 250.0), (rnd.uniform(0, aw), rnd.uniform(0, ah))]
                out["tr"][v] = {"ancho": aw, "alto": ah, "m": limpio(mp), "pp": limpio(pp),
                                "m2p": limpio([m2p(*p) for p in mp]), "p2m": limpio([p2m(*p) for p in pp])}
        vn = rnd.choice(["arriba", "frente", "costado", "trayectoria"])
        out["fig_none"] = {"vista": vn, "F": figs(d, None, vn)}
        # ---- 3D ----
        if T.man_t3_ok(d) or d.get("obst3d"):
            cont["escena3d"] += 1; esc = []
            variantes = [{"w": 900, "h": 600}]
            ob = T.man_obst3d(d)
            variantes.append({"w": rnd.choice([700, 900, 1280]), "h": rnd.choice([480, 600, 720]), "yaw": num(-180, 360, 1), "pitch": num(5, 85, 1),
                              "zoom": rnd.choice([1.0, num(0.5, 2.5)]), "sel": ["o", rnd.choice(ob)["i"]] if ob and rnd.random() < 0.7 else None,
                              "centro": [num(-10, 10), num(-10, 10)] if rnd.random() < 0.3 else None})
            for var in variantes:
                try:
                    ops, P, piso = T.man3d_escena(d, res, var["w"], var["h"], var.get("yaw", 35.0), var.get("pitch", 32.0), var.get("zoom", 1.0),
                                                  tuple(var["sel"]) if var.get("sel") else None, tuple(var["centro"]) if var.get("centro") else None)
                    pP = [(0.0, 0.0, 0.0), (3.0, -2.0, 1.5), (num(-20, 20), num(-20, 20), num(0, 10))]
                    pk = [(100.0, 200.0), (450.0, 300.0), (num(0, var["w"]), num(0, var["h"]))]
                    e = {"var": var, "ops": limpio(ops), "pP": limpio(pP), "P": limpio([P(*p) for p in pP]), "pk": limpio(pk),
                         "piso": limpio([piso(*p) for p in pk]), "marco": limpio(P.marco)}
                    # con marco (mientras se arrastra): el marco de esta escena, un poco corrido
                    mc = list(P.marco); mc[0] -= 1.0; mc[3] += 2.0
                    ops2, P2, _ = T.man3d_escena(d, res, var["w"], var["h"], var.get("yaw", 35.0), var.get("pitch", 32.0), var.get("zoom", 1.0), None, None, tuple(mc))
                    e["marco_in"] = limpio(mc); e["ops_marco"] = limpio(ops2); e["P_marco"] = limpio([P2(*p) for p in pP]); e["marco2"] = limpio(P2.marco)
                except Exception as ex:
                    e = {"var": var, "error": err(ex)}
                esc.append(e)
            out["esc"] = esc
            if res is None:
                pass
        # ---- man_ubicar ----
        ub = []
        for _ in range(3):
            W_, H_ = rnd.choice([(800, 500), (300, 200)])
            cajas = []
            for _c in range(rnd.randint(0, 10)):
                x = rnd.uniform(0, W_); y = rnd.uniform(0, H_); cajas.append([x, y, x + rnd.uniform(5, 160), y + rnd.uniform(5, 40)])
            if rnd.random() < 0.3: cajas = [[round(v) for v in c] for c in cajas]
            an, al = rnd.choice([rnd.uniform(10, 200), rnd.randint(10, 200)]), rnd.choice([rnd.uniform(8, 40), 14])
            x0, y0 = rnd.uniform(-20, W_), rnd.uniform(-20, H_)
            lim = [0, 0, W_, H_] if rnd.random() < 0.5 else None
            r_ = T.man_ubicar([tuple(c) for c in cajas], W_, H_, an, al, x0, y0, lim)
            a = cajas[0] if cajas else [0, 0, 10, 10]; b = [x0, y0, x0 + an, y0 + al]
            ub.append({"cajas": cajas, "w": W_, "h": H_, "ancho": an, "alto": al, "x0": x0, "y0": y0, "lim": lim, "r": limpio(r_),
                       "choque": T._man_cajas_choque(a, b), "choque0": T._man_cajas_choque(a, b, 0), "a": a, "b": b})
        out["ubicar"] = ub
        fh.write(json.dumps(out, ensure_ascii=False) + "\n")
        # ---- cobertura ----
        cont["casos"] += 1
        rr = res or {}
        if rr.get("config") == "viga" and rr.get("aparejo"): cont["separadores_aparejo"] += 1
        if d.get("usar_sep"): cont["usar_sep"] += 1
        if T.man_t3_ok(d): cont["tray3d"] += 1
        if d.get("obst3d"): cont["obst3d"] += 1
        if d.get("forma") == "Pieza irregular" and len(d.get("contorno") or []) >= 3: cont["pieza_irregular_contorno"] += 1
        if T.man_es_pluma(d.get("grua_tipo") if d.get("grua_tipo") in T.MAN_GRUAS else None): cont["pluma"] += 1
        else: cont["portico"] += 1
        if d.get("tipo_carga") == "Big bags" or str(d.get("forma")).startswith("Big bag"): cont["big_bag"] += 1
        if d.get("con_puntos") is False:
            cont["sin_puntos"] += 1
            if T.man_metodo_sp(d)[0] == "accesorio": cont["accesorio_sp"] += 1
        if int(d.get("grua_puntos") or 1) == 2: cont["grua_2_puntos"] += 1
        for c_, key in (("desv_gancho", "desv_gancho"), ("adyacentes", "adyacentes"), ("borde_3m", "borde_3m"), ("girar", "girar"), ("rebabas", "rebabas"),
                        ("h_disp", "h_disp"), ("obst_tray", "obst_tray")):
            if d.get(key): cont[c_] += 1
        if len(d.get("trayectoria") or []) > 0: cont["trayectoria_2d"] += 1
        if d.get("pintura") == "Con pintura especial": cont["pintura_especial"] += 1
        if int(T._man_f(d.get("ciclos"), 1)) >= T.MAN_CICLICA: cont["ciclica"] += 1
        if d.get("nivel") != T.MAN_NIVEL[0] and T._man_f(d.get("dif_nivel")) > 0: cont["nivel_distinto"] += 1
        if rr.get("pendulo"): cont["con_pendulo"] += 1

with open(SALIDA + ".cobertura.json", "w", encoding="utf-8") as fh:
    json.dump(cont, fh, ensure_ascii=False, indent=1)
print(json.dumps(cont, ensure_ascii=False))
