#!/usr/bin/env python

import os

def get_branch_name():
    return os.popen("git rev-parse --abbrev-ref HEAD").read().strip()

def is_new_branch():
    commits = os.popen("git rev-list --no-walk --exclude=refs/heads/" + get_branch_name() + " --exclude=HEAD --all").read().strip()
    log = os.popen(f"git log --all --not {commits}").read()
    return not bool(log.strip())

def is_problem_branch(branch_name):
    branch_name_parts = branch_name.split("/")
    if len(branch_name_parts) == 2 and branch_name_parts[0] == "problems" and branch_name_parts[1]:
        return True
    return False

def try_get_problem_name(branch_name):
    if not is_problem_branch(branch_name):
        return None
    return branch_name.split("/")[1]

def create_problem_template():
    branch_name = get_branch_name()
    if branch_name == "master" or not is_new_branch():
        return
    
    problem_name = try_get_problem_name(branch_name)
    if not problem_name:
        return
    
    build_generator_output = os.popen("dotnet build \"./submodules/ProblemTemplateGenerator/src/ProblemTemplateGenerator.Cli/ProblemTemplateGenerator.Cli.csproj\" -o \"./submodules/ProblemTemplateGenerator/src/ProblemTemplateGenerator.Cli/bin/\"").read()
    print(build_generator_output)
    generation_output = os.popen(f"\"./submodules/ProblemTemplateGenerator/src/ProblemTemplateGenerator.Cli/bin/ProblemTemplateGenerator.Cli.exe\" -s leetcode -n {problem_name}").read()
    print(generation_output)         

if __name__ == "__main__":
    create_problem_template()
