#!/usr/bin/env python

import json
import sys

from functools import reduce
from operator import mul
from pathlib import Path

percent_filled = float(sys.argv[1])
template_path = Path("templates/varied-fillings.json")

initial_cell_size = 4200

with template_path.open(encoding="utf-8") as template_file:
    config = json.load(template_file)

dims = [
    size * count
    for size, count
    in zip(config["Geometry"]["blocksize"], config["Geometry"]["blockcount"])
]
total_volume = reduce(mul, dims, 1)
target_volume = total_volume * percent_filled / 100
n_cells = int(target_volume // initial_cell_size)
# If n_cells is odd, second type gets one more cell
n_cells_first_type = n_cells // 2
n_cells_second_type = n_cells - n_cells_first_type
edge_length = int(target_volume ** (1 / 3))
offsets = [
    (dims[0] - edge_length) // 2,
    (dims[1] - edge_length) // 2,
    (dims[2] - edge_length) // 2
]

print(f"Target volume: {target_volume} ({percent_filled}%, edge length: {edge_length}), # of cells: {n_cells}", file=sys.stderr)

if target_volume > 0:
    config["Filling"]["cells"].append({
        "shape": "cube",
        "pattern": "voronoi",
        "box": [
            offsets,
            [
                min(offsets[0] + edge_length, dims[0] - 1),
                min(offsets[1] + edge_length, dims[1] - 1),
                min(offsets[2] + edge_length, dims[2] - 1)
            ]
        ],
        "count": n_cells,
        "celltype": [0, 0, n_cells_first_type, n_cells_second_type]
    })

json.dump(config, sys.stdout, indent=2)
