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

def parse_markdown_table(md_file_path):
    """
    Reads a Markdown file containing a pipeseparated table.
    Returns a list of rows (each row is a list of strings).
    """
    with open(md_file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # Remove empty lines and strip trailing/leading spaces
    lines = [line.strip() for line in lines if line.strip()]

    # Find the first line that looks like a table header (contains '|')
    table_lines = []
    for line in lines:
        if line.startswith('|') and line.endswith('|'):
            table_lines.append(line)

    if not table_lines:
        raise ValueError("No Markdown table found in the file.")

    # Parse rows: split by '|', strip each cell
    rows = []
    for line in table_lines:
        # Remove leading/trailing '|' and split
        cells = line[1:-1].split('|')
        cells = [cell.strip() for cell in cells]
        rows.append(cells)

    # The second line (index 1) is the separator row (|---|----|)
    # Remove it if present
    if len(rows) >= 2 and all(re.match(r'^[-:]+$', cell) for cell in rows[1] if cell):
        rows.pop(1)

    return rows

def sanitize_text(text):
    """Replace common problematic Unicode symbols with ASCII equivalents."""
    replacements = {
        '\u2192': '->',   # 
        '\u2013': '-',    # –
        '\u2014': '-',    # —
        '\u2212': '-',    # 
        '\u00D7': 'x',    # ×
        '\u2026': '...',  # …
    }
    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.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
            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():
    # Read the Markdown table from node.md
    md_file = 'node.md'   # Change to your file name if different
    table_data = parse_markdown_table(md_file)

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

    # Optional: also save as CSV for reference
    with open('nodes_converted.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerows(table_data)
    print(" Converted Markdown table to 'nodes_converted.csv'")

    # Create DXF drawing
    doc = ezdxf.new('R2010')
    manual_widths = [40, 80, 40, 40, 60]   # 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)
    doc.saveas('table_output.dxf')
    print(" table_output.dxf created successfully")

if __name__ == '__main__':
    main()
