"""md2csv.py: each Markdown table in a .md file (for example our Actor's output) to its own CSV file.

Needs Python 3 only.
Run: python md2csv.py statement.md [more.md ...]
It writes statement-table-1.csv, statement-table-2.csv, ... next to each file, and never overwrites a file.
From https://brasspage.com/pdf-to-csv/
"""

import csv
import sys
from pathlib import Path

if len(sys.argv) < 2:
    sys.exit(__doc__)

for name in sys.argv[1:]:
    md = Path(name)
    tables, rows = [], []
    for line in md.read_text(encoding="utf-8").splitlines() + [""]:
        if line.startswith("|"):
            if not set(line.replace(" ", "")) <= set("|-:"):  # skip the |---|---| line
                rows.append(
                    [
                        c.strip().replace("\\|", "|")
                        for c in line.strip()[1:-1].split(" | ")
                    ]
                )
        elif rows:
            tables.append(rows)
            rows = []
    if not tables:
        print(f"{md}: no table found")
    for i, rows in enumerate(tables, 1):
        out = md.with_name(f"{md.stem}-table-{i}.csv")
        if out.exists():
            print(f"{out}: exists, skipped")
            continue
        with out.open("w", newline="", encoding="utf-8") as f:
            csv.writer(f).writerows(rows)
        print(out)
