"""Illustrative Shannon entropy of a diffusing field on a prescribed 2D grid.

The lattice and update rule are assumptions of this toy model. It does not
derive spacetime geometry or provide an empirical test of IPT.
"""

import argparse
from pathlib import Path

import numpy as np


INIT_TYPES = ("spike", "stripe", "noise", "gradient")


def validate_parameters(grid_size, steps, alpha, observer, radius, init_type, seed=None):
    """Reject inputs that do not define this nonnegative diffusion model."""
    if not isinstance(grid_size, (int, np.integer)) or grid_size < 2:
        raise ValueError("grid size must be an integer of at least 2")
    if not isinstance(steps, (int, np.integer)) or steps < 1:
        raise ValueError("steps must be an integer of at least 1")
    if not np.isfinite(alpha) or not 0 <= alpha <= 0.25:
        raise ValueError("alpha must be finite and between 0 and 0.25 inclusive")
    if len(observer) != 2 or any(
        not isinstance(value, (int, np.integer)) or not 0 <= value < grid_size
        for value in observer
    ):
        raise ValueError("observer x and y must be integers inside the grid")
    if not isinstance(radius, (int, np.integer)) or radius < 0:
        raise ValueError("observer radius must be a nonnegative integer")
    if init_type not in INIT_TYPES:
        raise ValueError("initialization must be one of: " + ", ".join(INIT_TYPES))
    if seed is not None and (not isinstance(seed, (int, np.integer)) or seed < 0):
        raise ValueError("seed must be a nonnegative integer")


def initialize_grid(grid_size, init_type, seed=None):
    grid = np.zeros((grid_size, grid_size))
    if init_type == "spike":
        grid[grid_size // 2, grid_size // 2] = 100.0
    elif init_type == "stripe":
        grid[grid_size // 2] = 50.0
    elif init_type == "noise":
        # Preserve the original unseeded generator; an explicit seed is local.
        if seed is None:
            values = np.random.rand(grid_size, grid_size)
        else:
            values = np.random.default_rng(seed).random((grid_size, grid_size))
        grid = values * 10
    elif init_type == "gradient":
        for i in range(grid_size):
            for j in range(grid_size):
                grid[i, j] = np.exp(
                    -((i - grid_size / 2) ** 2 + (j - grid_size / 2) ** 2) / 100
                )
    else:
        raise ValueError("unknown initialization: " + str(init_type))
    return grid


def compute_entropy(grid):
    """Shannon entropy in nats after normalizing nonnegative field weights."""
    if not np.all(np.isfinite(grid)) or np.any(grid < 0):
        raise ValueError("entropy requires finite, nonnegative field weights")
    total = np.sum(grid)
    if total <= 0:
        return 0.0
    probabilities = grid[grid > 0] / total
    return float(-np.sum(probabilities * np.log(probabilities)))


def run_simulation(grid_size, steps, alpha, observer, radius, init_type, seed=None):
    validate_parameters(grid_size, steps, alpha, observer, radius, init_type, seed)
    grid = initialize_grid(grid_size, init_type, seed)
    entropy_global, entropy_local, frames = [], [], []
    y, x = np.ogrid[:grid_size, :grid_size]
    mask = (x - observer[0]) ** 2 + (y - observer[1]) ** 2 <= radius ** 2

    for _ in range(steps):
        entropy_global.append(compute_entropy(grid))
        # The window is normalized separately, rather than being an additive
        # contribution to whole-grid entropy. The window itself does not wrap.
        entropy_local.append(compute_entropy(grid * mask))
        frames.append(grid.copy())
        neighbors = (
            np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0)
            + np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1)
        )
        # Equivalent to the original periodic Laplacian update, expressed as
        # nonnegative weights for the permitted range of alpha.
        grid = (1 - 4 * alpha) * grid + alpha * neighbors
    return frames, entropy_global, entropy_local


def plot_entropy(entropy_global, entropy_local, steps, output_dir=".", show=True):
    import matplotlib.pyplot as plt

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    fig, ax = plt.subplots(figsize=(8, 4))
    ax.plot(entropy_global, label="Whole grid")
    ax.plot(entropy_local, label="Observer window (renormalized)")
    ax.set(
        xlabel="Step", ylabel="Shannon entropy (nats)",
        title="Illustrative diffusion: normalized field entropy",
    )
    ax.legend()
    fig.tight_layout()
    path = output_dir / "entropy_trend.png"
    fig.savefig(path)
    if show:
        plt.show()
    plt.close(fig)
    return path


def save_animation(frames, observer, radius, output_dir="."):
    import matplotlib.animation as animation
    import matplotlib.pyplot as plt

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    fig, ax = plt.subplots()
    cax = ax.imshow(
        frames[0], cmap="inferno", interpolation="nearest",
        vmin=0, vmax=max(float(np.max(frames[0])), 1e-12),
    )
    ax.add_patch(plt.Circle(observer, radius, color="white", fill=False))
    fig.colorbar(cax, ax=ax, label="Field amplitude")

    def update(i):
        ax.set_title(f"Illustrative field diffusion: step {i}")
        cax.set_data(frames[i])
        return cax,

    ani = animation.FuncAnimation(fig, update, frames=len(frames), interval=100)
    path = output_dir / "entropy_evolution.gif"
    ani.save(path, writer="pillow")
    plt.close(fig)
    return path


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--grid", type=int, default=60, help="Grid width and height (at least 2)")
    parser.add_argument("--steps", type=int, default=150, help="Frames including the initial state (at least 1)")
    parser.add_argument("--alpha", type=float, default=0.2, help="Diffusion coefficient, 0 to 0.25 inclusive")
    parser.add_argument(
        "--obs", nargs=3, type=int, metavar=("X", "Y", "RADIUS"),
        help="Observer window; defaults to the grid center and radius up to 8",
    )
    parser.add_argument("--init", choices=INIT_TYPES, default="spike")
    parser.add_argument("--seed", type=int, help="Nonnegative random seed for reproducible noise")
    parser.add_argument("--output-dir", type=Path, default=Path("."), help="Directory for PNG/GIF output")
    parser.add_argument("--no-show", action="store_true", help="Save files without opening a plotting window")
    args = parser.parse_args(argv)
    observer = args.obs or [
        args.grid // 2, args.grid // 2, min(8, max(0, (args.grid - 1) // 2))
    ]
    try:
        validate_parameters(
            args.grid, args.steps, args.alpha, observer[:2], observer[2], args.init, args.seed
        )
    except ValueError as error:
        parser.error(str(error))

    if args.no_show:
        import matplotlib
        matplotlib.use("Agg")
    try:
        frames, global_entropy, local_entropy = run_simulation(
            args.grid, args.steps, args.alpha, tuple(observer[:2]),
            observer[2], args.init, args.seed,
        )
        output_dir = args.output_dir.expanduser().resolve()
        gif_path = save_animation(frames, tuple(observer[:2]), observer[2], output_dir)
        plot_path = plot_entropy(
            global_entropy, local_entropy, args.steps, output_dir, show=not args.no_show
        )
    except (OSError, ValueError) as error:
        parser.exit(1, f"Simulation failed: {error}\n")
    print(f"Saved {plot_path}\nSaved {gif_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
