#!/usr/bin/python3 -s

import argparse
import re
import sys
import subprocess
import webbrowser


def fetch_remote(path):
    remote_parser = re.compile(r"^(?P<name>\w+)\s(?P<url>.+)\s(\(fetch\)|\(push\))")

    try:
        output = subprocess.check_output(["git", "-C", path, "remote", "-v"]).decode("utf-8")
    except subprocess.CalledProcessError:
        sys.exit(0)

    lines = output.split("\n")
    lines = [line for line in lines if line]

    remotes = []
    for line in lines:
        parsed_line = remote_parser.match(line)
        if parsed_line:
            remotes.append((parsed_line.group("name"), parsed_line.group("url")))

    remotes = set(remotes)

    return {remote: url for remote, url in remotes}


def parse_remote(remote_url):
    match = None

    if remote_url is None:
        print("Invalid remote")
        sys.exit(0)
    elif remote_url.startswith("https://"): # avoid having to potentially use both regexs
        match = re.match(r"^https://(?P<domain>\w+.\w+)/(?P<username>.+)/(?P<repository>.+).git$", remote_url)
    else:
        match = re.match(r"^git@(?P<domain>\w+.\w+):(?P<username>.+)/(?P<repository>.+).git$", remote_url)

    if not match:
        print("Could not parse remote url")
        sys.exit(0)

    url = "http://{domain}/{username}/{repository}".format(**match.groupdict())

    webbrowser.open_new_tab(url)


def parse_args():
    parser = argparse.ArgumentParser(description="A command line utility for opening a repositories remote homepage.")
    parser.add_argument("-r", "--remote", required=False, help="remote to open. default: origin")
    parser.add_argument("path", nargs="?", default=".", help="path to local repository, defaults to '.'")
    args = parser.parse_args()

    return vars(args)

def main():
    args = parse_args()

    remotes = fetch_remote(args["path"])

    remote = None
    if remotes.get(args["remote"]):
        remote = remotes[args["remote"]]
    elif remotes.get("origin"):
        remote = remotes["origin"]
    elif len(remotes.keys()) <= 1:
        for value in remotes.values():
            remote = value
            break
    else:
        print("No remotes found")
        sys.exit(0)

    parse_remote(remote)


main()
