import os
from pathlib import Path

root_dir = "experiments/debugging_gemini/16-Apr/classifieds/runs"


def consolidate_error_files(root_dir, output_file="consolidated_errors.txt"):
    # Find all error.txt files
    error_files = list(Path(root_dir).rglob("error.txt"))

    # Create or overwrite the output file
    with open(output_file, "w", encoding="utf-8") as outfile:
        for i, error_file in enumerate(error_files, 1):
            # Write a separator with the file path
            outfile.write(f"\n{'=' * 80}\n")
            outfile.write(f"Error file {i}: {error_file}\n")
            outfile.write(f"{'=' * 80}\n\n")

            # Read and write the contents of each error file
            try:
                with open(error_file, "r", encoding="utf-8") as infile:
                    outfile.write(infile.read())
                outfile.write("\n")
            except Exception as e:
                outfile.write(f"Failed to read file: {str(e)}\n")

    print(f"Consolidated {len(error_files)} error files into {output_file}")


# Usage example
if __name__ == "__main__":
    # Use the current directory as the root directory
    consolidate_error_files(root_dir)
