import random
from typing import Dict, List, Tuple


def _get_preset_cells(preset: str, cols: int = 100, rows: int = 60, density: float = 0.18) -> Dict[Tuple[int, int], int]:
    """
    Initializes living cells for a given preset pattern.
    Living cells are represented as a dictionary mapping (col, row) coordinates to age (1 for newborn).
    """
    cx, cy = cols // 2, rows // 2
    grid: Dict[Tuple[int, int], int] = {}

    preset_clean = (preset or "gosper").lower()

    if preset_clean == 'random':
        for r in range(rows):
            for c in range(cols):
                if random.random() < density:
                    grid[(c, r)] = 1
        return grid

    if preset_clean == 'gosper':
        # Gosper Glider Gun pattern
        gun = [
            (1, 5), (1, 6), (2, 5), (2, 6),
            (11, 5), (11, 6), (11, 7), (12, 4), (12, 8), (13, 3), (13, 9), (14, 3), (14, 9),
            (15, 6), (16, 4), (16, 8), (17, 5), (17, 6), (17, 7), (18, 6),
            (21, 3), (21, 4), (21, 5), (22, 3), (22, 4), (22, 5), (23, 2), (23, 6),
            (25, 1), (25, 2), (25, 6), (25, 7),
            (35, 3), (35, 4), (36, 3), (36, 4)
        ]
        ox = cx - 18
        oy = cy - 5
        for x, y in gun:
            grid[((ox + x) % cols, (oy + y) % rows)] = 1

    elif preset_clean == 'pulsar':
        # Pulsar (Period 3 oscillator)
        coords = [
            (-6, -4), (-6, -3), (-6, -2), (-6, 2), (-6, 3), (-6, 4),
            (-4, -6), (-4, -1), (-4, 1), (-4, 6),
            (-3, -6), (-3, -1), (-3, 1), (-3, 6),
            (-2, -6), (-2, -1), (-2, 1), (-2, 6),
            (-1, -4), (-1, -3), (-1, -2), (-1, 2), (-1, 3), (-1, 4),
            (1, -4), (1, -3), (1, -2), (1, 2), (1, 3), (1, 4),
            (2, -6), (2, -1), (2, 1), (2, 6),
            (3, -6), (3, -1), (3, 1), (3, 6),
            (4, -6), (4, -1), (4, 1), (4, 6),
            (6, -4), (6, -3), (6, -2), (6, 2), (6, 3), (6, 4)
        ]
        for dx, dy in coords:
            grid[((cx + dx) % cols, (cy + dy) % rows)] = 1

    elif preset_clean == 'gliders':
        # Glider fleet
        fleet = [(5, 5), (20, 5), (35, 5), (50, 5), (65, 5)]
        pattern = [(1, 0), (2, 1), (0, 2), (1, 2), (2, 2)]
        for fx, fy in fleet:
            for dx, dy in pattern:
                grid[((fx + dx) % cols, (fy + dy) % rows)] = 1

    elif preset_clean == 'acorn':
        # Acorn (Methuselah)
        acorn = [(1, 0), (3, 1), (0, 2), (1, 2), (4, 2), (5, 2), (6, 2)]
        ox = cx - 3
        oy = cy - 1
        for dx, dy in acorn:
            grid[((ox + dx) % cols, (oy + dy) % rows)] = 1

    else:
        # Default fallback to Gosper gun
        return _get_preset_cells('gosper', cols=cols, rows=rows, density=density)

    return grid


def _step_grid(grid: Dict[Tuple[int, int], int], cols: int, rows: int, max_age: int = 16) -> Tuple[Dict[Tuple[int, int], int], int]:
    """
    Advances the grid state by one generation using Conway's B3/S23 rules with toroidal wrapping.
    Living cells age up to max_age.
    Returns the next grid state and the count of newborns.
    """
    neighbor_counts: Dict[Tuple[int, int], int] = {}
    for (x, y) in grid:
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                if dx == 0 and dy == 0:
                    continue
                nx = (x + dx) % cols
                ny = (y + dy) % rows
                neighbor_counts[(nx, ny)] = neighbor_counts.get((nx, ny), 0) + 1

    next_grid: Dict[Tuple[int, int], int] = {}
    newborns = 0

    for pos, count in neighbor_counts.items():
        if pos in grid:
            # Live cell survives if it has 2 or 3 live neighbors
            if count in (2, 3):
                next_grid[pos] = min(max_age, grid[pos] + 1)
        else:
            # Dead cell becomes newborn if it has exactly 3 live neighbors
            if count == 3:
                next_grid[pos] = 1
                newborns += 1

    return next_grid, newborns


def simulate_conway(
    generations: int = 300,
    preset: str = "gosper",
    cols: int = 100,
    rows: int = 60,
    density: float = 0.18,
    max_age: int = 16
) -> List[dict]:
    """
    Simulates Conway's Game of Life with 16-level grayscale age decay for the requested generations.
    Returns a list of frame objects:
    [
        {
            "gen": generation_number,
            "pop": total_alive_cells,
            "newborns": newly_born_cells_this_step,
            "cells": [[col, row, age], ...]
        },
        ...
    ]
    Sensible practice: Computing generations on the server guarantees reproducible physics,
    avoids taxing client CPU/battery, and delivers an immediate playback stream.
    """
    grid = _get_preset_cells(preset, cols=cols, rows=rows, density=density)
    frames: List[dict] = []
    step_newborns = sum(1 for (c, r), age in grid.items() if age == 1)

    for gen in range(generations):
        cells = [
            [c, r, age]
            for (c, r), age in sorted(grid.items(), key=lambda item: (item[0][1], item[0][0]))
        ]
        newborns = sum(1 for c in cells if c[2] == 1) if gen == 0 else step_newborns
        frames.append({
            "gen": gen,
            "pop": len(cells),
            "newborns": newborns,
            "cells": cells,
        })

        grid, step_newborns = _step_grid(grid, cols=cols, rows=rows, max_age=max_age)

    return frames


simulate_game_of_life = simulate_conway
