#!/usr/bin/env python3
# AUTHOR: Daesorin
# CREATED: 2026-07-28 11:14 +0100

import csv
import sys

# INPUT VALIDATION
# ensure an input file argument is provided
if len(sys.argv) < 2:
    print("usage: md2csv <input.md>")
    sys.exit(1)

input_file = sys.argv[1]

# TABLE CONVERSION
# open input markdown and initialize standard output csv writer
with open(input_file, "r", encoding="utf-8") as infile:
    writer = csv.writer(sys.stdout)

    for line in infile:
        line = line.strip()

        # ROW FILTERING
        # skip empty lines and markdown layout separator lines
        if not line or "---" in line:
            continue

        # CELL EXTRACTION
        # check if line represents a markdown table row
        if line.startswith("|") and line.endswith("|"):
            # strip leading and trailing pipes then split by delimiter
            raw_cells = line[1:-1].split("|")
            cleaned_cells = [cell.strip() for cell in raw_cells]
            writer.writerow(cleaned_cells)
