#!/usr/bin/python3

import subprocess
from pathlib import Path
import csvspoon._cli

here = Path(__file__).absolute().parent

with open(here / "README.md", "w", encoding="utf8") as fout:
    with open(here / ".README_header.md", encoding="utf8") as fin:
        for l in fin:
            fout.write(l)

    fout.write(csvspoon._cli.cli_example_main_doc())  # pylint: disable=protected-access

    fout.write("## Cli usage\n")
    res = subprocess.run(["csvspoon", "-h"], capture_output=True, check=False)
    if res.returncode != 0:
        raise ValueError
    print("```", file=fout)
    print(res.stdout.decode("utf8"), file=fout)
    print("```", file=fout)

    for subcommand in sorted(
        ("cat", "apply", "filter", "sort", "join", "aggregate", "sample")
    ):
        print(f"### csvspoon {subcommand}", file=fout)
        res = subprocess.run(
            ["csvspoon", subcommand, "-h"], capture_output=True, check=False
        )
        if res.returncode != 0:
            raise ValueError
        print("```", file=fout)
        print(res.stdout.decode("utf8"), file=fout)
        print("```", file=fout)
