#!/usr/bin/env python3

"""
Devops functions for this package. Includes functions for automated
package deployment, changelog generation, and changelog checking.

This script is generated by the template at
https://github.com/AmbitionEng/python-library-template

Do not change this script! Any fixes or updates to this script should be made
to https://github.com/AmbitionEng/python-library-template
"""

import os
import subprocess
import sys
from typing import IO, Any, TypeAlias, Union


File: TypeAlias = Union[IO[Any], int, None]


def _shell(
    cmd: str,
    check: bool = True,
    stdin: File = None,
    stdout: File = None,
    stderr: File = None,
):  # pragma: no cover
    """Runs a subprocess shell with check=True by default"""
    return subprocess.run(cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr)


def _publish_to_pypi() -> None:
    """
    Uses poetry to publish to pypi
    """
    if "PYPI_USERNAME" not in os.environ or "PYPI_PASSWORD" not in os.environ:
        raise RuntimeError("Must set PYPI_USERNAME and PYPI_PASSWORD env vars")

    _shell("poetry config http-basic.pypi ${PYPI_USERNAME} ${PYPI_PASSWORD}")
    _shell("poetry build")
    _shell("poetry publish -vvv -n", stdout=subprocess.PIPE)


def deploy() -> None:
    """Deploys the package and uploads documentation."""
    # Ensure proper environment
    if not os.environ.get("CIRCLECI"):  # pragma: no cover
        raise RuntimeError("Must be on CircleCI to run this script")

    _publish_to_pypi()

    print("Deployment complete.")


if __name__ == "__main__":
    if sys.argv[-1] == "deploy":
        deploy()
    else:
        raise RuntimeError(f'Invalid subcommand "{sys.argv[-1]}"')
