from gitrepo import GitRepository
import datetime
import os
import sys

if len(sys.argv) > 1:
    config_path = sys.argv[1]
    if config_path.endswith(".py"):
        config_path = config_path[:-3]
    config = __import__(config_path)
else:
    try:
        import generate_config as config
    except ImportError:
        print("Please fill the generate_config.py file or pass the config file as argument")
        sys.exit(1)

def gen_from_issue():
    """
    To use this function, you need to fill some information in `generate_config.py`

    Hint: you can copy `generate_config.py.example` to `generate_config.py` and fill the information.
    """
    output_file_path = "output/" + config.repo_name.replace("/", "_") + "_" + config.specific_commit_sha + ".json"
    output = {}
    output["Type"] = config.bug_type
    output["ErrorMessage"] = config.error_msg
    output["Issue"] = config.issue
    output["Explain"] = config.explain
    output["Command"] = config.command

    repo_url = "https://github.com/" + config.repo_name
    clone_dir = "tmp"

    git_repo = GitRepository(repo_url, clone_dir)
    changes_info = git_repo.get_changed_functions_in_commit(config.specific_commit_sha)

    commit = git_repo.get_patch_info_for_commit(config.specific_commit_sha)
    patch_info = git_repo.generate_patch(commit)

    file_contents_before_commit = git_repo.get_file_contents_before_commit(config.specific_commit_sha)
    token_num = git_repo.get_token(file_contents_before_commit)

    output["RepoName"] = config.repo_name
    output["CommitSHA"] = config.specific_commit_sha
    output["Time"] = datetime.datetime.fromtimestamp(commit["date"]).strftime("%Y-%m-%d")
    output["Difficulty"] = "Difficult"
    output["OriginCode"] = output["BuggyCode"] = file_contents_before_commit
    output["Patch"] = patch_info
    output["BuggyCodeLocation"] = changes_info  # file function content_all content_change
    output["Source"] = "Commit"
    output["Token"] = token_num

    if os.path.exists(output_file_path):
        overwrite = input("The output file already exists, do you want to overwrite it? [y/N]")
        if overwrite.lower() != "y":
            print("Exit without overwriting the file")
            return
    git_repo.save_to_json(output, output_file_path)

if __name__ == '__main__':
    gen_from_issue()