"""
Solución dirigida: detecta entidades LINE/ARC cuyo "tamaño" (radio del arco,
o longitud de la línea) es muy pequeño -comparado con el resto del dibujo-
y les fuerza un lineweight mínimo absoluto, para que matplotlib no las
engorde hasta convertirlas en blobs sólidos.

Es el mismo script de conversión original, con un paso extra justo antes
de renderizar.
"""

import sys
import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
from ezdxf.addons.drawing.config import Configuration, LineweightPolicy, BackgroundPolicy, ColorPolicy
import matplotlib.pyplot as plt

entrada = sys.argv[1] if len(sys.argv) > 1 else "plano.dxf"
salida = sys.argv[2] if len(sys.argv) > 2 else "plano_fix.svg"

# Umbral: cualquier ARC con radio menor que esto se considera "pequeño"
# (remache/tornillo) y se le fuerza lineweight mínimo.
# Ajusta este valor según tus unidades de dibujo (aquí, ~0.2 porque tus
# radios problemáticos eran 0.06-0.16).
RADIO_UMBRAL = 0.2

# Lineweight a forzar en esas entidades pequeñas, en centésimas de mm
# (es la unidad que usa DXF: 25 = 0.25mm, 13 = 0.13mm, 5 = 0.05mm...)
LINEWEIGHT_FORZADO = 5

doc = ezdxf.readfile(entrada)
msp = doc.modelspace()


def fix_dimpost_override(entity):
    if not entity.has_xdata("ACAD"):
        return False
    tags = list(entity.get_xdata("ACAD"))
    new_tags = []
    changed = False
    i = 0
    while i < len(tags):
        tag = tags[i]
        if (
            tag.code == 1070
            and tag.value == 3
            and i + 1 < len(tags)
            and tags[i + 1].code == 1000
        ):
            changed = True
            i += 2
            continue
        new_tags.append(tag)
        i += 1
    if changed:
        entity.set_xdata("ACAD", new_tags)
    return changed


dims = list(msp.query("DIMENSION"))
ok = 0
fallidas = []
for e in dims:
    try:
        e.render()
        ok += 1
    except Exception as ex:
        if "dimpost" in str(ex).lower() and fix_dimpost_override(e):
            try:
                e.render()
                ok += 1
                continue
            except Exception as ex2:
                fallidas.append((e.dxf.handle, f"tras limpiar dimpost: {ex2}"))
                continue
        fallidas.append((e.dxf.handle, str(ex)))
print(f"Cotas renderizadas correctamente: {ok}/{len(dims)}")
for handle, msg in fallidas:
    print(f"  FALLO handle={handle}: {msg}")

# --- NUEVO: forzar lineweight mínimo en arcos pequeños ---
afectados = 0
for e in msp.query("ARC"):
    if e.dxf.radius < RADIO_UMBRAL:
        e.dxf.lineweight = LINEWEIGHT_FORZADO
        afectados += 1

for e in msp.query("LINE"):
    p1 = e.dxf.start
    p2 = e.dxf.end
    longitud = ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5
    if longitud < RADIO_UMBRAL * 2:
        e.dxf.lineweight = LINEWEIGHT_FORZADO
        afectados += 1

print(f"Entidades pequeñas con lineweight forzado a {LINEWEIGHT_FORZADO}: {afectados}")

# --- Render igual que antes, pero con ABSOLUTE para respetar ---
# --- el lineweight que acabamos de forzar ---
fig = plt.figure(figsize=(20, 20))
ax = fig.add_axes([0, 0, 1, 1])
ctx = RenderContext(doc)
backend = MatplotlibBackend(ax)
config = Configuration().with_changes(
    max_flattening_distance=0.00002,
    background_policy=BackgroundPolicy.WHITE,
    lineweight_policy=LineweightPolicy.ABSOLUTE,
)
frontend = Frontend(ctx, backend, config=config)
frontend.draw_layout(msp, finalize=True)
fig.savefig(salida, format="svg")
print(f"Guardado: {salida}")
