#!/usr/bin/env python3

import argparse
import os
import re
import subprocess
from typing import Optional


def _convert_to_http(url):
    url = re.sub(r"^git@", "https://", url)
    url = re.sub(r"\.com:", ".com/", url)
    url = re.sub(r"\.org:", ".org/", url)
    url = re.sub(r".git$", "", url)
    return url


def _run_git_command(args):
    # command = ["git"] + args
    command = ["git", args]
    devnull = open(os.devnull)
    output = subprocess.check_output(command, stderr=devnull)
    devnull.close()
    return output.decode().strip()


def _get_remotes():
    remotes = set()
    lines = [line for line in _run_git_command(["remote", "-v"]).split("\n") if line]
    for line in lines:
        name, url, _ = line.split()
        remotes.add((name, _convert_to_http(url)))

    return remotes


# TODO: Remove this
def _get_remote(name, remotes):
    return next(
        (url for remote_name, url in remotes if name == remote_name),
        None,
    )


def _get_sha() -> str:
    return _run_git_command([
        "git",
        "rev-parse",
        "HEAD",
    ])


def _get_upstream(branch: Optional[str] = None):
    return _run_git_command([
        "rev-parse",
        "--abbrev-ref",
        "--symbolic-full-name",
        f"{branch if branch else ''}@{{upstream}}",
    ])


def _get_upstream_branch(branch: Optional[str] = None):
    return _get_upstream(branch).split("/", 1)[-1]


def _get_tracked_remote() -> Optional[str]:
    try:
        return _get_upstream().split("/", 1)[0]
    except subprocess.CalledProcessError:
        return None


def _get_ref(ref):
    try:
        return _run_git_command(["rev-parse", ref])
    except subprocess.CalledProcessError:
        return None


def _is_branch(ref):
    try:
        _run_git_command(["show-ref", f"refs/heads/{ref}"])
        return True
    except subprocess.CalledProcessError:
        return False


def main(args):
    remotes = _get_remotes()
    remote = args.remote or "origin"
    try:
        remote_url = next(url for (name, url) in remotes if name == remote)
    except StopIteration:
        raise SystemExit(f"error: no remote named: {remote}")

    # tracked_remote = args.remote or _get_tracked_remote() or "origin"
    # try:
    #     # TODO: use tracked remote in the cases that's useful, forks vs not is the key
    #     tracked_remote_url = next(
    #         url for (name, url) in remotes if name == tracked_remote
    #     )
    # except StopIteration:
    #     raise SystemExit(f"error: no remote named: {tracked_remote}")

    if not args.argument:
        url = remote_url
    elif os.path.exists(args.argument):
        try:
            ref = _get_upstream_branch()
        except subprocess.CalledProcessError:
            ref = _get_sha()
        url = "{}/blob/{}/{}".format(remote_url, ref, args.argument)
    elif _is_branch(args.argument):
        url = "{}/tree/{}".format(remote_url, args.argument)
    elif _get_ref(args.argument):
        url = "{}/commit/{}".format(remote_url, _get_ref(args.argument))
    elif remote_arg := _get_remote(args.argument, remotes):
        url = remote_arg
    elif args.argument in ("mp", "pulls"):
        query = "pulls?q=is%3Aopen+is%3Apr"
        if args.argument == "mp":
            query = f"{query}+author%3Akeith"
        if args.argument2:
            arg_string = args.argument2.replace(" ", "+")
            query = f"{query}+{arg_string}"
        url = os.path.join(remote_url, query)
    elif args.argument == "mi":
        url = os.path.join(remote_url, "issues/keith")
    elif args.argument == "pr":
        upstream = _get_upstream_branch()
        if upstream in ("master", "main"):
            branch_name = _run_git_command(["pilebranchname", "HEAD"])
            upstream = _get_upstream_branch(branch_name)

        query = f"pulls?q=is%3Aopen+is%3Apr+head%3A{upstream}"
        url = os.path.join(remote_url, query)
    elif args.argument == "issues":
        query = "issues"
        if args.argument2:
            query = f"{query}?q=is%3Aissue+is%3Aopen+{args.argument2}"

        url = os.path.join(remote_url, query)
    elif args.argument == "r":
        url = os.path.join(remote_url, "releases")
    else:
        url = os.path.join(remote_url, args.argument)

    subprocess.check_call(["open", url])


def _get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-r",
        "--remote",
        default=None,
        type=str,
        help="The name of the remote to open",
    )
    parser.add_argument("argument", nargs="?", help="The argument to try and open")
    parser.add_argument("argument2", nargs="?", help="The argument to try and open")
    return parser


if __name__ == "__main__":
    main(_get_parser().parse_args())
