
import json
import csv
import sys

def json_to_csv(json_file_path, csv_file_path):
    """
    Converts a JSON file containing a list of objects to a CSV file.
    """
    try:
        with open(json_file_path, 'r') as f:
            data = json.load(f)

        if not isinstance(data, list) or not data:
            print("Error: JSON file should contain a non-empty list of objects.")
            return

        # Get all unique headers from all objects in the list
        headers = set()
        for item in data:
            headers.update(item.keys())
        headers = sorted(list(headers))

        with open(csv_file_path, 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=headers)
            writer.writeheader()
            writer.writerows(data)

        print(f"Successfully converted {json_file_path} to {csv_file_path}")

    except FileNotFoundError:
        print(f"Error: The file {json_file_path} was not found.")
    except json.JSONDecodeError:
        print(f"Error: Could not decode JSON from the file {json_file_path}.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python json_to_csv.py <input_json_file> <output_csv_file>")
    else:
        json_to_csv(sys.argv[1], sys.argv[2])
