import ezdxf
from ezdxf.enums import TextEntityAlignment
import csv
import sys
import re

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

def parse_markdown_table(md_file):
    """Parse a markdown table file and return the table data."""
    with open(md_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Find the first markdown table in the file
    table_match = re.search(r'\|(.+)\|\n\|(.*?)\|\n((?:\|.*?\|\n)+)', content)
    if not table_match:
        raise ValueError("No markdown table found in the file")

    # Extract rows
    rows = []
    for row_str in table_match.group(3).strip().split('\n'):
        # Remove leading/trailing | and split by |
        cells = [cell.strip() for cell in row_str.strip('|').split('|')]
        rows.append(cells)

    return rows

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

        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():
    if len(sys.argv) != 2:
        print("Usage: python md_table_to_dxf_utf.py <input_file.md>")
        sys.exit(1)

    input_file = sys.argv[1]

    try:
        # Parse markdown table
        table_data = parse_markdown_table(input_file)

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

        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_data, table_origin=(0, 0), row_height=6.0, col_widths=manual_widths, vertical_offset=-1.0)
        output_file = input_file.replace('.md', '.dxf')
        doc.saveas(output_file)
        print(f"✅ {output_file} created")
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()
