#!/usr/bin/python3
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'python'))

import subprocess

from slaby_scripts.git import run_git_command
from termcolor import colored


def get_branches() -> list[str]:
    p = run_git_command('for-each-ref', '--format=%(refname:short)', 'refs/heads/')
    return p.stdout.splitlines()

def check_commit(commit: str) -> bool:
    try:
        subprocess.run(['git', 'rev-parse', '--verify', commit], stdout=subprocess.DEVNULL,
                       stderr=subprocess.DEVNULL, check=True)
        return True
    except subprocess.CalledProcessError:
        return False

def pending(branch: str) -> str | None:
    user=f"origin/users/jslaby/{branch}/for-next"
    if not check_commit(user):
        return None

    try:
        run_git_command('merge-base', '--is-ancestor', branch, user, exit_on_error=False,
                        capture_output=False)
    except subprocess.CalledProcessError:
        return None
    return user

def dump_state(color: str, state: str, rev: str, note: str | None) -> None:
    state = f"[{state}]"
    print(colored(f"{state:18}{rev}{note or ''}", color))

def check_branch(branch: str) -> None:
    upstream=f"origin/{branch}"
    if not check_commit(upstream):
        dump_state("light_yellow", "NOT_PRESENT", branch, None)
        return

    try:
        run_git_command('merge-base', '--is-ancestor', branch, upstream, exit_on_error=False,
                        capture_output=False)
        dump_state("light_green", "MERGED", branch, None)
    except subprocess.CalledProcessError:
        p=pending(branch)
        dump_state("light_red", "UNMERGED", f"{upstream}..{branch}",
                   f" (pending at {p})" if p else None)

for branch in get_branches():
    check_branch(branch)
