from typing import Any

import json
import os


def main():
    delete_files_with_empty_explanations('data')


def delete_files_with_empty_explanations(data_dir: str) -> int:
    """
    Recursively scan data_dir for .json files. Delete any file containing
    an 'explanations' key with an empty list as its value.
    Returns the number of files deleted.
    """
    files_checked = 0
    files_deleted = 0
    for root, _, files in os.walk(data_dir):
        for filename in files:
            if not filename.endswith('.json'):
                continue
            file_path = os.path.join(root, filename)
            files_checked += 1
            try:
                with open(file_path, 'r') as f:
                    data = json.load(f)
                if contains_empty_explanations(data):
                    os.remove(file_path)
                    print(f"Deleted: {file_path}")
                    files_deleted += 1
            except Exception as e:
                print(f"Failed to process {file_path}: {e}")
    print(f"Checked {files_checked} files. Deleted {files_deleted} files.")
    return files_deleted


def contains_empty_explanations(obj: Any) -> bool:
    """
    Recursively check if a JSON object contains a key 'explanations' with an empty list as its value.
    """
    if isinstance(obj, dict):
        for key, value in obj.items():
            if key == 'explanations' and value == []:
                return True
            if contains_empty_explanations(value):
                return True
    elif isinstance(obj, list):
        for item in obj:
            if contains_empty_explanations(item):
                return True
    return False


if __name__ == "__main__":
    main()
