# -*- coding: utf-8 -*-
import ezdxf
from ezdxf.enums import TextEntityAlignment
import csv
import sys

def sanitize_text(text):
    """Replace common problematic Unicode symbols with ASCII equivalents."""
    # Use Unicode escapes to keep the source code ASCII-only
    replacements = {
        '\u2192': '->',   #  right arrow
        '\u2013': '-',    # – en dash
        '\u2014': '-',    # — em dash
        '\u2212': '-',    #  minus sign
        '\u00D7': 'x',    # × multiplication sign
        '\u2026': '...',  # … ellipsis
    }
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text

def add_table_to_dxf(doc, table_data, 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.4

    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

        # Horizontal lines
        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]

            # Vertical lines
            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}
            )

            # Text positioning
            center_x = x_start + col_widths[j] / 2.0
            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():
    if len(sys.argv) != 2:
        print("Usage: python csv_table_to_dxf_utf.py <input_file.csv>")
        sys.exit(1)

    input_file = sys.argv[1]

    # Read CSV with explicit UTF-8 encoding
    with open(input_file, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        table_data = [row for row in reader]

    # Sanitize all cells
    table_data = [[sanitize_text(cell) for cell in row] for row in table_data]

    doc = ezdxf.new('R2010')
    manual_widths = [40, 80, 40, 40, 60]
    # Negative offset moves text DOWN; adjust as needed
    add_table_to_dxf(doc, table_data, table_origin=(0, 0), row_height=6.0, col_widths=manual_widths, vertical_offset=-1.0)
    output_file = input_file.replace('.csv', '.dxf')
    doc.saveas(output_file)
    print(f'✅ {output_file} created successfully')

if __name__ == '__main__':
    main()
