#!/usr/bin/python3

import subprocess
import tempfile
import os


def parse_autoflake_py() -> tuple[str, list[str]]:
    lines: list[str] = []
    for line in open("bleak/__init__.py"):
        if lines:
            if lines and "parser.parse_args" in line:
                break
            lines.append(line)
            continue

        if "argparse.ArgumentParser" in line:
            lines.append(line)
            continue

    return lines


def argparse_pyfile():
    lines = parse_autoflake_py()
    return f"""
import argparse

def get_argparse():
{"".join(lines)}
    return parser
"""


def get_argparse_manpage_cmd(filename):
    return [
        "argparse-manpage",
        "--pyfile",
        filename,
        "--function",
        "get_argparse",
        "--author",
        "Henrik Blidh",
        "--author-email",
        "henrik.blidh@nedomkull.com",
        "--project-name",
        "bleak",
        "--url",
        "https://github.com/hbldh/bleak",
    ]


def run_argparse_manpage():
    with tempfile.TemporaryDirectory() as dir_tmp:
        filename = os.path.join(dir_tmp, "bleak")
        tmp = open(filename, "w")
        tmp.write(argparse_pyfile())
        tmp.flush()
        cmd = get_argparse_manpage_cmd(filename)
        p = subprocess.run(cmd, text=True, capture_output=True)
        os.remove(filename)
        return p.stdout.splitlines()


def build_manpage():
    manpage = run_argparse_manpage()
    for line in manpage:
        if line == "bleak":
            print("bleak \- Bluetooth Low Energy platform agnostic client")
            continue
        print(line)


if __name__ == "__main__":
    build_manpage()
