from typing import List, Dict
from pathlib import Path
import json
import itertools
from investigation import investigation_home, cwd, storage_path, entry_path


def scan_cases(commit_hash: str = "", batch_hash: List[str] = []) -> Dict[str, Dict]:
    assert not (commit_hash == "" and batch_hash != ""), "Commit hash cannot be empty if batch hash is provided."

    commits: List[Path] = []
    if (commit_hash == ""):
        commits.extend(storage_path.glob("???????"))
    else:
        commits.append(storage_path / commit_hash)

    batch_matchs = []
    if (len(batch_hash) == 0):
        batch_matchs.append("????????.json")
    else:
        for bh in batch_hash:
            batch_matchs.append(f"{bh}.json")

    existing_jobs: Dict[str, Dict] = {}
    for commit_folder, batch_match in itertools.product(commits, batch_matchs):
        for job_file in commit_folder.glob(batch_match):
            for job_hash, job_config in json.loads(job_file.read_text()).items():
                if (batch_hash == ""):
                    job_config["batch_hash"] = job_file.stem
                if (commit_hash == ""):
                    job_config["commit_hash"] = commit_folder.stem
                existing_jobs[job_hash] = job_config
    return existing_jobs
