# SPDX-FileCopyrightText: (c) 2024 EvalPlus Team
#
# SPDX-License-Identifier: Apache-2.0

import json
import os
import subprocess
from pathlib import Path

import git
import tempdir
from fire import Fire
from tqdm.auto import tqdm

TOOL_JAR_PATH = (
    Path(__file__).resolve().parent
    / "java-analysis"
    / "java-lib"
    / "java-analysis-1.0-SNAPSHOT.jar"
)


CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

# dataset_path is the dataset generated by dataset_ensemble_clone.py
def main():
    with open("scripts/cherrypick/lists.json") as f:
        lists = json.load(f)

    repos = lists["java"]
    for repo in tqdm(repos):
        repo_name = repo["repo"]
        commit_sha = repo["commit_sha"]
        entrypoint = repo["entrypoint_path"]
        print(f"Visiting https://github.com/{repo_name}/tree/{commit_sha}")

        with tempdir.TempDir() as temp_dir:
            gh_repo = git.Repo.clone_from(
                f"https://github.com/{repo_name}.git",
                temp_dir,
            )
            gh_repo.git.checkout(commit_sha)

            output_dependency = {}
            abs_prefix = os.path.join(temp_dir, entrypoint)
            for java_file in Path(abs_prefix).rglob("*.java"):
                command_list = f"java -jar {TOOL_JAR_PATH} {temp_dir} {entrypoint} {java_file.absolute()}".split()
                # cd `temp_dir`` and capture the output
                output = subprocess.check_output(command_list, cwd=temp_dir)
                dependencies = output.decode("utf-8").strip().split("\n")

                if dependencies:
                    if "" in dependencies:
                        dependencies.remove("")
                    output_dependency[
                        java_file.relative_to(Path(temp_dir)).as_posix()
                    ] = dependencies
                else:
                    output_dependency[
                        java_file.relative_to(Path(temp_dir)).as_posix()
                    ] = []

            repo["dependency"] = output_dependency

    with open(os.path.join(CURRENT_DIR, "data", "java.json"), "w") as f_out:
        json.dump({"java": repos}, f_out)


if __name__ == "__main__":
    Fire(main)
