import re
import sys
import csv

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('|')]
        # Filter out empty cells that might result from splitting
        cells = [cell for cell in cells if cell]
        rows.append(cells)

    return rows

def main():
    if len(sys.argv) != 2:
        print("Usage: python md_to_csv.py <input_file.md>")
        sys.exit(1)

    input_file = sys.argv[1]

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

        # Generate output filename
        output_file = input_file.replace('.md', '.csv')

        # Write to CSV
        with open(output_file, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerows(table_data)

        print(f"✅ {output_file} created successfully")
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()
