import ezdxf
from ezdxf.enums import TextEntityAlignment
import csv

def sanitize_text(text):
    replacements = {
        '→': '->',
        '×': 'x',
        '–': '-',
        '—': '-',
    }
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

with open("nodes.csv", "r") as f:
    reader = csv.reader(f)
    table_data = list(reader)

table_data = [[sanitize_text(str(cell)) for cell in row] for row in table_data]

def add_table_to_dxf(doc, table_origin=(0, 0), row_height=5.0, col_widths=None, vertical_offset=0.0):
    msp = doc.modelspace()
    rows = len(table_data)
    cols = len(table_data[0]) if rows > 0 else 0

    if col_widths is None:
        col_widths = []
        for c in range(cols):
            max_len = max(len(str(row[c])) for row in table_data)
            col_widths.append(max_len * 1.5)

    text_height = row_height * 0.6

    try:
        if 'TableText' not in doc.styles:
            doc.styles.new('TableText', font='Arial.ttf')
        text_style = 'TableText'
    except:
        text_style = 'Standard'

    for i, row in enumerate(table_data):
        y_top = table_origin[1] - i * row_height
        y_bottom = y_top - row_height

        msp.add_line((table_origin[0], y_top),
                     (table_origin[0] + sum(col_widths), y_top),
                     dxfattribs={'color': 7})
        if i == rows - 1:
            msp.add_line((table_origin[0], y_bottom),
                         (table_origin[0] + sum(col_widths), y_bottom),
                         dxfattribs={'color': 7})

        x_start = table_origin[0]
        for j, cell in enumerate(row):
            x_end = x_start + col_widths[j]

            if j == 0:
                msp.add_line((x_start, y_top), (x_start, y_bottom),
                             dxfattribs={'color': 7})
            msp.add_line((x_end, y_top), (x_end, y_bottom),
                         dxfattribs={'color': 7})

            center_x = x_start + col_widths[j] / 2.0
            # Apply vertical offset (positive = up, negative = down)
            center_y = y_top - row_height / 2.0 + vertical_offset

            text = msp.add_text(str(cell), dxfattribs={
                'height': text_height,
                'style': text_style,
            })
            text.set_placement((center_x, center_y), align=TextEntityAlignment.CENTER)

            x_start = x_end

def main():
    doc = ezdxf.new('R2010')
    manual_widths = [40, 80, 40, 40, 60]
    # Try a negative offset to move text DOWN (e.g., -1.0)
    add_table_to_dxf(doc, table_origin=(0, 0), row_height=6.0, col_widths=manual_widths, vertical_offset=-1.0)
    doc.saveas("table_output.dxf")
    print("✅ table_output.dxf created")

if __name__ == "__main__":
    main()