from region import Region
from output_layer_2d import OutputLayer2D


def run_demo(total_steps: int = 5, log_every: int = 5, rng_seed: int = 42):
    h = w = 8
    region = Region("py_image_io")
    l_in = region.add_input_layer_2d(h, w, 1.0, 0.01)
    l_hid = region.add_layer(16, 4, 2)
    l_out = region.add_output_layer_2d(h, w, 0.20)
    region.bind_input("pixels", [l_in])
    region.connect_layers(l_in, l_hid, 0.05, False)
    region.connect_layers(l_hid, l_out, 0.10, False)

    import random
    rnd = random.Random(rng_seed)

    for step in range(total_steps):
        # generate sparse frame
        frame = [[1.0 if rnd.random() > 0.95 else 0.0 for _ in range(w)] for _ in range(h)]
        m = region.tick_2d("pixels", frame)

        if log_every > 0 and (step + 1) % log_every == 0:
            out_layer = region.get_layers()[l_out]
            if isinstance(out_layer, OutputLayer2D):
                image = out_layer.get_frame()
                sum_value = sum(sum(row) for row in image)
                print(f"[{step+1:02d}] delivered={m.delivered_events} out_mean={sum_value / (h * w):.3f}")
