#!/usr/bin/python3

import subprocess
import tempfile
import sys


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

        if "argparse.ArgumentParser" in line:
            line = line.replace("ArgumentParser(", 'ArgumentParser(prog="telegram-send", ')
            lines.append(line)
            continue

    return lines


def argparse_pyfile():
    lines = parse_py()
    version = open("telegram_send/version.py").read()
    if not lines:
        print("can't build manpage")
        sys.exit(1)
    return f"""
import argparse
import sys
sys.path.append(".")
{version}

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


def get_argparse_manpage_cmd(filename):
    return [
        "argparse-manpage",
        "--pyfile",
        filename,
        "--function",
        "get_argparse",
        "--author",
        "Rahiel Kasim",
        "--author-email",
        "rahielkasim@gmail.com",
        "--project-name",
        "telegram-send",
        "--url",
        "https://github.com/rahiel/telegram-send",
    ]


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


def build_manpage():
    manpage = run_argparse_manpage()
    for line in manpage:
        if line == "telegram-send":
            print(
                "telegram-send \-",
                "send messages and files over Telegram from the command-line",
            )
            continue
        print(line)

if __name__ == "__main__":
    build_manpage()
