import os
import json

# ========= CONFIG =========
# Hard-coded path to your big JSON file
INPUT_FILE = r"2025_12_10_11_idInquilino_212_20251210110013.json"
# Max size per output file in bytes (100 MB)
MAX_BYTES = 100 * 1024 * 1024
# ==========================


def main():
    if not os.path.isfile(INPUT_FILE):
        print(f"Input file not found: {INPUT_FILE}")
        return

    dir_name, filename = os.path.split(INPUT_FILE)
    base_name, ext = os.path.splitext(filename)
    if not ext:
        ext = ".json"

    print(f"Reading JSON from: {INPUT_FILE} ...")
    with open(INPUT_FILE, "r", encoding="utf-8") as f:
        data = json.load(f)

    if not isinstance(data, list):
        raise ValueError("Root JSON is not an array (expected: [ {...}, {...} ])")

    print(f"Total items in array: {len(data)}")

    chunk = []
    current_bytes = 2  # for the surrounding brackets "[]"
    chunk_index = 1

    def write_chunk(items, index):
        if not items:
            return
        out_path = os.path.join(
            dir_name,
            f"{base_name}-output-{index:04d}{ext}"
        )
        with open(out_path, "w", encoding="utf-8") as out_f:
            json.dump(items, out_f, ensure_ascii=False)
        print(f"Wrote {out_path} with {len(items)} items")

    for item in data:
        # Serialize single item to estimate size impact
        item_json = json.dumps(item, ensure_ascii=False)
        sep_bytes = 1 if chunk else 0  # comma between elements
        projected = current_bytes + sep_bytes + len(item_json)

        # If adding this item would exceed the limit and we already have some items,
        # flush current chunk and start a new one.
        if projected > MAX_BYTES and chunk:
            write_chunk(chunk, chunk_index)
            chunk_index += 1
            chunk = []
            current_bytes = 2  # reset for "[]"
            sep_bytes = 0  # first element in new file

        # Add item to current chunk
        chunk.append(item)
        current_bytes += sep_bytes + len(item_json)

    # Write last chunk
    write_chunk(chunk, chunk_index)

    print("Done!")


if __name__ == "__main__":
    main()
