#!/usr/bin/env python

import os
import sys
import webbrowser

if __name__ == '__main__':
    file_path = os.path.realpath(__file__)
    github_dir = os.path.dirname(file_path)
    root_dir = os.path.dirname(github_dir)
    sys.path.insert(0, root_dir)

from util import github_util
from util.root import git_root


PAGES = ['', 'issues', 'pulls', 'commits', 'wiki', 'pulse', 'graphs']


def usage():
    sys.stderr.write('''Usage: %s [page]|<path>

Where page is one of {%s}. If page is not specified, opens the repo root.
If you pass in a path, it will open that file in the GitHub code browser.
''' % (sys.argv[0], ', '.join(PAGES[1:])))
    sys.exit(1)


def relative_to_root(path):
    """Takes any path and returns one relative to the git root.

    This is important when running `github <path>` from a subdirectory.
    """
    abspath = os.path.abspath(path)
    absroot = os.path.abspath(git_root())
    p = os.path.relpath(abspath, absroot)
    assert '..' not in p, '%s not under\n%s' % (abspath, absroot)
    return p


if __name__ == '__main__':
    if len(sys.argv) > 2:
        usage()

    remotes = github_util.get_github_remotes()
    if len(remotes) == 0:
        sys.stderr.write("There are no github remotes for this repo, "
                         "or perhaps you're not in a git repo.\n")
        sys.exit(1)

    remote = remotes[0].path
    if len(remotes) > 1:
        chosen_remote = remotes[0].path
        sys.stderr.write('Found multiple remotes. Using %s\n' % chosen_remote)

    repo_url = github_util.make_github_url(remote)

    arg = sys.argv[1] if len(sys.argv) > 1 else ''
    if arg in PAGES:
        url = '%s/%s' % (repo_url, arg)
    elif os.path.exists(arg):
        url = '%s/blob/master/%s' % (repo_url, relative_to_root(arg))
    else:
        usage()

    webbrowser.open_new_tab(url)
    sys.exit(0)
