# generated via claude https://claude.ai/share/6fa0a62f-6f31-44e0-9227-e4dec86524ea

import os
import json
import argparse
from glob import glob


def process_json_files(input_dir, output_dir=None):
    """
    Process JSON files to replace empty time strings with null values.

    Args:
        input_dir: Directory containing the JSON files to process
        output_dir: Directory to save the processed files (if None, will overwrite original files)
    """
    # Create output directory if specified and doesn't exist
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)

    # Find all JSON files in the input directory
    json_files = glob(os.path.join(input_dir, "*.json"))

    for file_path in json_files:
        # Read the JSON file
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)

        # Process each stop in the file
        if "_links" in data and "stops" in data["_links"]:
            for stop in data["_links"]["stops"]:
                if "times" in stop:
                    for time_entry in stop["times"]:
                        # Replace empty time strings with null
                        if "time" in time_entry and time_entry["time"] == "":
                            time_entry["time"] = None

        # Determine where to save the processed file
        if output_dir:
            # Save to new directory with same filename
            filename = os.path.basename(file_path)
            output_path = os.path.join(output_dir, filename)
        else:
            # Overwrite original file
            output_path = file_path

        # Write the processed data back to file
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)

        print(f"Processed {file_path} -> {output_path}")


def main():
    parser = argparse.ArgumentParser(
        description="Process JSON files to replace empty time strings with null values"
    )
    parser.add_argument("input_dir", help="Directory containing JSON files to process")
    parser.add_argument(
        "--output_dir",
        help="Directory to save processed files (if not specified, will overwrite original files)",
    )

    args = parser.parse_args()

    process_json_files(args.input_dir, args.output_dir)
    print("Processing complete!")


if __name__ == "__main__":
    main()
