#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import subprocess
import sys
import textwrap
from typing import Optional

from jinja2 import Environment, FileSystemLoader

from pipx.main import __version__


def get_help(pipxcmd: Optional[str]) -> str:
    cmd = [sys.executable, "-m", "pipx"]
    if pipxcmd:
        cmd.append(pipxcmd)
    cmd.append("--help")

    helptext = (
        subprocess.run(cmd, stdout=subprocess.PIPE, check=True)
        .stdout.decode()
        .replace(os.path.expanduser("~"), "~")
    )
    return f"""
```
{" ".join(cmd)}
{helptext}
```
"""


params = {
    "usage": get_help(None),
    "runpip": get_help("runpip"),
    "install": get_help("install"),
    "upgrade": get_help("upgrade"),
    "upgradeall": get_help("upgrade-all"),
    "inject": get_help("inject"),
    "uninstall": get_help("uninstall"),
    "uninstallall": get_help("uninstall-all"),
    "reinstallall": get_help("reinstall-all"),
    "list": get_help("list"),
    "run": get_help("run"),
    "version": __version__,
}

warning = textwrap.dedent(
    """
        <!---
        Do not edit this file. This file was rendered from the
        templates/ directory.
        See Contributing for how to update this file.
        --->
        """
).lstrip()

env = Environment(loader=FileSystemLoader("templates"))

with open("docs/docs.md", "w") as f:
    f.write(warning)
    f.write(env.get_template("docs.md").render(**params))
    f.write("\n")
