import os
import json

# Directory containing your original JSON files
INPUT_DIR = os.path.dirname(os.path.abspath(__file__))
# Subdirectory for the modified files
OUTPUT_DIR = os.path.join(INPUT_DIR, "extended_2x_div_logs")

# Create the output directory if it doesn't exist
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Iterate over all files in the input directory
for filename in os.listdir(INPUT_DIR):
    # Only process JSON files that start with "div_logs_"
    if not filename.lower().startswith("div_logs_") or not filename.lower().endswith('.json'):
        continue

    input_path = os.path.join(INPUT_DIR, filename)
    output_path = os.path.join(OUTPUT_DIR, filename)

    # Load the JSON content
    with open(input_path, 'r', encoding='utf-8') as f:
        try:
            data = json.load(f)
        except json.JSONDecodeError as e:
            print(f"Skipping {filename}: failed to parse JSON ({e})")
            continue

    # Process each entry in the JSON array
    if isinstance(data, list):
        for entry_index, entry in enumerate(data):
            coords_wrapper = entry.get('coordinates')
            if (isinstance(coords_wrapper, dict)
                    and 'coordinates' in coords_wrapper
                    and isinstance(coords_wrapper['coordinates'], list)):
                for rect_index, rect in enumerate(coords_wrapper['coordinates']):
                    # Only adjust rectangles with all needed keys
                    if not all(k in rect for k in ('x', 'y', 'width', 'height')):
                        continue

                    # Skip rectangles with zero width or height
                    if rect['width'] == 0 or rect['height'] == 0:
                        print(f"Warning: {filename}, entry {entry_index}, rect {rect_index} skipped due to zero width/height ({rect['width']}x{rect['height']})")
                        continue

                    # Calculate enlarged coordinates
                    new_x = rect['x'] - 44
                    new_y = rect['y'] - 22
                    new_width = rect['width'] + 88
                    new_height = rect['height'] + 44

                    # Print warnings if coordinates go below zero
                    if new_x < 0:
                        print(f"Warning: {filename}, entry {entry_index}, rect {rect_index} -> x < 0 ({new_x})")
                    if new_y < 0:
                        print(f"Warning: {filename}, entry {entry_index}, rect {rect_index} -> y < 0 ({new_y})")

                    # Apply the adjusted values
                    rect['x'] = new_x
                    rect['y'] = new_y
                    rect['width'] = new_width
                    rect['height'] = new_height

    # Write the modified data to the output file
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    print(f"Processed {filename} -> extended/{filename}")
