#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import os.path
import subprocess
from typing import Sequence

HERE = os.path.dirname(os.path.realpath(__file__))
SSH = 'git@github.com:'
DOT_GIT = '.git'


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('--remote', default='')
    parser.add_argument('--upstream', default='')
    args = parser.parse_args(argv)

    cmd = (
        os.path.join(HERE, '_git-remote-upstream'),
        '--remote', args.remote, '--upstream', args.upstream,
    )
    remote, upstream = json.loads(subprocess.check_output(cmd))

    url_cmd = ('git', 'config', f'remote.{upstream}.url')
    remote_url = subprocess.check_output(url_cmd).decode().strip()
    if remote_url.startswith(SSH):
        remote_url = remote_url[len(SSH):]
    if remote_url.endswith(DOT_GIT):
        remote_url = remote_url[:-1 * len(DOT_GIT)]

    branch_cmd = ('git', 'rev-parse', '--abbrev-ref', 'HEAD')
    branch_name = subprocess.check_output(branch_cmd).decode().strip()
    if remote != upstream:
        branch_name = f'{remote}:{branch_name}'
    print(f'https://github.com/{remote_url}/compare/{branch_name}?expand=1')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
