#!/usr/bin/python3

import subprocess
import tempfile


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

        if line.startswith("__version__"):
            version_line = line
            continue

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

    return version_line, lines


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

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


def get_argparse_manpage_cmd(filename):
    return [
        "argparse-manpage",
        "--pyfile",
        filename,
        "--function",
        "get_argparse",
        "--author",
        "Steven Myint",
        "--author-email",
        "git@stevenmyint.com",
        "--project-name",
        "autoflake",
        "--url",
        "https://github.com/PyCQA/autoflake",
    ]


def run_argparse_manpage():
    with tempfile.NamedTemporaryFile(mode="w") as tmp:
        tmp.write(argparse_pyfile())
        tmp.flush()
        cmd = get_argparse_manpage_cmd(tmp.name)
        p = subprocess.run(cmd, text=True, capture_output=True)
        return p.stdout.splitlines()


def build_manpage():
    manpage = run_argparse_manpage()
    for line in manpage:
        if line == "autoflake":
            print(
                "autoflake \- removes unused imports and unused variables in Python code"
            )
            continue
        if line == ".SH OPTIONS":
            print(".SH DESCRIPTION")
            print(
                "Removes unused imports and unused variables as reported by pyflakes."
            )
        print(line)

if __name__ == "__main__":
    build_manpage()
