#!/usr/bin/env cached-nix-shell
#! nix-shell -i python3
#! nix-shell -p python3 python3Packages.gitpython

"""
glab wrapper for jujutsu
"""

import json
import pathlib
import pprint
import subprocess
import sys

import git


def git_repo() -> git.Repo:
    directory = pathlib.Path.cwd()
    for parent in [directory] + list(directory.parents):
        if parent.joinpath(".git").is_dir():
            break
    else:
        raise FileNotFoundError("Not a git repository")
    return git.Repo(parent.as_posix())

def current_branch() -> str:
    # FIXME
    # Need to extract this from jj, can do with jj log --no-graph -T 'commit_id'
    # (see templates) or show, also see revsets.
    # How to search is a good question, usually it will be before @,
    # but when editing it will be after.
    # How to deal with nested MRs? (at least fail in that case)

    # sp = subprocess.run(
    #     ["glab", "mr", "view", branch, "--output", "json"], stdout=subprocess.PIPE
    # )
    return "pouet"


def mr_info(branch: str) -> dict:
    sp = subprocess.run(
        ["glab", "mr", "view", branch, "--output", "json"], stdout=subprocess.PIPE
    )
    return json.loads(sp.stdout)


def to_glab() -> None:
    subprocess.run(["glab"] + sys.argv[1:])


if sys.argv[1] == "mr":
    branch = current_branch()
    # TODO If no number specified, add it
    if sys.argv[2] == "checkout":
        data = mr_info(branch)
        pprint.pprint(data)
        # TODO If no commit on the branch, then create a jj one and make it have the title of the issue,
        # also the branch name
    else:
        to_glab()
else:
    to_glab()

# TODO Push command that signs and pushes to the right repo

# TODO Autocomplete