#!/usr/bin/env python3
"""Exact finite example of observation, waiting, and unresolved calibration.

This is an engineered, noiseless two-pixel measurement model, not an
astronomical simulation, a consciousness model, or a test of CE's superiority.
"""

import argparse
import json
from dataclasses import asdict, dataclass
from pathlib import Path


STATES = ((1, 0), (0, 1))


@dataclass(frozen=True)
class World:
    state: tuple[int, int]
    swapped: bool


@dataclass(frozen=True)
class Observation:
    source_epoch: int
    received_epoch: int
    value: int
    reference: tuple[int, int] | None = None


def measurement_row(source_epoch: int, swapped: bool) -> tuple[int, int]:
    """Even epochs expose a sum view; odd epochs expose a difference view."""
    if source_epoch % 2 == 0:
        return (1, 1)
    return (-1, 1) if swapped else (1, -1)


def prediction(world: World, observation: Observation) -> int:
    state = world.state if observation.reference is None else observation.reference
    row = measurement_row(observation.source_epoch, world.swapped)
    return sum(weight * component for weight, component in zip(row, state))


def observe(
    world: World,
    source_epoch: int,
    delay: int = 0,
    reference: tuple[int, int] | None = None,
) -> Observation:
    if source_epoch < 0 or delay < 0:
        raise ValueError("Epoch and propagation delay must be nonnegative")
    template = Observation(source_epoch, source_epoch + delay, 0, reference)
    return Observation(
        source_epoch, source_epoch + delay, prediction(world, template), reference
    )


def compatible_worlds(
    observations: tuple[Observation, ...],
    possible_swaps: tuple[bool, ...] = (False,),
) -> tuple[World, ...]:
    candidates = tuple(
        World(state, swapped) for state in STATES for swapped in possible_swaps
    )
    return tuple(
        world
        for world in candidates
        if all(
            prediction(world, record) == record.value
            for record in observations
        )
    )


def received_by(
    observations: tuple[Observation, ...], epoch: int
) -> tuple[Observation, ...]:
    return tuple(record for record in observations if record.received_epoch <= epoch)


def describe_case(
    observations: tuple[Observation, ...],
    possible_swaps: tuple[bool, ...] = (False,),
) -> dict:
    survivors = compatible_worlds(observations, possible_swaps)
    return {
        "observations": [asdict(record) for record in observations],
        "surviving_worlds": [asdict(world) for world in survivors],
        "surviving_object_count": len({world.state for world in survivors}),
    }


def results() -> dict:
    truth = World((1, 0), False)
    first = observe(truth, 0)
    difference = observe(truth, 1)
    calibration = observe(truth, 1, reference=(1, 0))
    delayed = tuple(observe(truth, epoch, delay=10) for epoch in (0, 1))
    cases = {
        "single_sum_view": describe_case((first,)),
        "same_archived_record_replayed": describe_case((first,) * 5),
        "fresh_sum_view_at_epoch_2": describe_case((first, observe(truth, 2))),
        "wait_for_difference_view_at_epoch_1": describe_case((first, difference)),
        "both_views_unknown_wiring": describe_case((first, difference), (False, True)),
        "both_views_plus_known_reference": describe_case(
            (first, difference, calibration), (False, True)
        ),
        "delay_10_received_by_9": describe_case(received_by(delayed, 9)),
        "delay_10_received_by_10": describe_case(received_by(delayed, 10)),
        "delay_10_received_by_11": describe_case(received_by(delayed, 11)),
    }
    return {
        "status": "exact illustration, not empirical validation",
        "assumptions": [
            "Only two static candidate objects: (1,0) and (0,1)",
            "Known engineered view schedule: sum at even epochs, difference at odd epochs",
            "No noise; propagation delay is known and recorded separately",
            "Unknown wiring, when allowed, is one fixed left/right swap",
            "Calibration assumes a known reference and unchanged wiring",
            "Inference uses record values and source epochs, never the hidden true state",
        ],
        "cases": cases,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, help="Optional JSON results path")
    args = parser.parse_args()
    rendered = json.dumps(results(), indent=2) + "\n"
    if args.output is None:
        print(rendered, end="")
    else:
        args.output.write_text(rendered, encoding="utf-8")


if __name__ == "__main__":
    main()
