import os
import sys

import git

from conductor.cli.args import build_arg_parser
from conductor.cli.cmd.clean import clean
from conductor.cli.cmd.deploy import deploy
from conductor.cli.cmd.init import init
from conductor.cli.cmd.mwaa_login import mwaa_login
from conductor.internal.utils import get_project_root


def main() -> None:
    cwd = os.getcwd()

    # Look for the git-related envvars.
    if not (
        "CONDUCTOR_GIT_BRANCH" in os.environ and "CONDUCTOR_COMMIT_HASH" in os.environ
    ):
        # If they don't exist, attempt to read the values assuming we are in a git repo.
        try:
            git.Repo(cwd, search_parent_directories=True)
        except git.exc.InvalidGitRepositoryError:  # type: ignore
            sys.exit(f"The current dir {cwd} is not inside a git repo.")
        # Set the environment variables if we are in a git repo
        repo = git.Repo(cwd, search_parent_directories=True)
        os.environ["CONDUCTOR_GIT_BRANCH"] = repo.active_branch.name
        os.environ["CONDUCTOR_COMMIT_HASH"] = repo.head.commit.hexsha

    # Adds the current directory into path so that modules can be imported.
    project_root = get_project_root()
    sys.path.append(project_root)

    parser = build_arg_parser()
    args = parser.parse_args()
    os.environ["CONDUCTOR_ENV"] = args.env

    if args.command == "deploy":
        deploy(project_root, selected_dag_name=args.dag)
    elif args.command == "init":
        init(project_root)
    elif args.command == "mwaa-login":
        mwaa_login(project_root)
    elif args.command == "clean":
        clean(project_root, dry_run=args.dry_run)
