#!/usr/bin/env python3
"""Independent standard-library replay of born_outcome_frontier.py.

This verifier deliberately does not import the production module. It rebuilds
the composite-null inequality checks, conditional data-processing checks,
synthetic likelihood-ratio paths, Kraft penalties, and power approximation
from their definitions. Agreement is implementation evidence, not physical
evidence for a hidden quantum variable.
"""

from __future__ import annotations

import math
import random
from statistics import NormalDist


ALPHA = 2.87e-7
BASE_SEED = 20_260_915
RUN_TRIALS = 120_000
PROPERTY_TRIALS = 5_000


def normalized(values: list[float]) -> list[float]:
    total = sum(values)
    if total <= 0 or any(value < 0 for value in values):
        raise ValueError("invalid nonnegative weights")
    return [value / total for value in values]


def independent_mutual_information(table: list[list[float]]) -> float:
    joint_total = sum(sum(row) for row in table)
    joint = [[value / joint_total for value in row] for row in table]
    rows = [sum(row) for row in joint]
    columns = [
        sum(row[column] for row in joint) for column in range(len(joint[0]))
    ]
    return sum(
        probability * math.log(probability / (rows[i] * columns[j]))
        for i, row in enumerate(joint)
        for j, probability in enumerate(row)
        if probability > 0
    )


def independent_coarsening(
    table: list[list[float]], labels: list[int]
) -> list[list[float]]:
    output_count = len(table[0])
    result = [[0.0] * output_count for _ in range(max(labels) + 1)]
    for label, row in zip(labels, table):
        for output, value in enumerate(row):
            result[label][output] += value
    return result


def independent_property_replay() -> tuple[float, float]:
    generator = random.Random(BASE_SEED + 2)
    maximum_multiplier = 0.0
    maximum_information_excess = -math.inf
    for _ in range(PROPERTY_TRIALS):
        output_count = generator.randint(2, 6)
        null = normalized(
            [generator.expovariate(1.0) for _ in range(output_count)]
        )
        envelope = [
            probability + generator.random() * (1 - probability)
            for probability in null
        ]
        candidate = normalized(
            [generator.expovariate(1.0) for _ in range(output_count)]
        )
        multiplier = sum(
            probability * wager / upper
            for probability, wager, upper in zip(null, candidate, envelope)
        )
        if multiplier > 1 + 1e-12:
            raise AssertionError("composite-null supermartingale bound failed")
        maximum_multiplier = max(maximum_multiplier, multiplier)

        lift_count = generator.randint(2, 8)
        joint = [
            [generator.expovariate(1.0) for _ in range(output_count)]
            for _ in range(lift_count)
        ]
        labels = [
            generator.randrange(generator.randint(1, lift_count + 1))
            for _ in range(lift_count)
        ]
        full_information = independent_mutual_information(joint)
        coarse_information = independent_mutual_information(
            independent_coarsening(joint, labels)
        )
        excess = coarse_information - full_information
        if excess > 1e-12:
            raise AssertionError("conditional data processing failed")
        maximum_information_excess = max(maximum_information_excess, excess)
    return maximum_multiplier, maximum_information_excess


def independent_binary_path(seed: int, hidden_lift: bool) -> tuple[float, float]:
    generator = random.Random(seed)
    accuracy = 0.51
    log_e = 0.0
    maximum = 0.0
    for _ in range(RUN_TRIALS):
        lift_bit = generator.randrange(2)
        if hidden_lift:
            outcome = (
                lift_bit if generator.random() < accuracy else 1 - lift_bit
            )
        else:
            outcome = generator.randrange(2)
        correct = outcome == lift_bit
        log_e += math.log(2 * (accuracy if correct else 1 - accuracy))
        maximum = max(maximum, log_e)
    return log_e, maximum


def independent_power_count(accuracy: float, code_bits: int) -> tuple[int, int]:
    correct_log = math.log(2 * accuracy)
    wrong_log = math.log(2 * (1 - accuracy))
    mean = accuracy * correct_log + (1 - accuracy) * wrong_log
    variance = (
        accuracy * (correct_log - mean) ** 2
        + (1 - accuracy) * (wrong_log - mean) ** 2
    )
    threshold = math.log(1 / ALPHA) + code_bits * math.log(2)
    expected = math.ceil(threshold / mean)
    z = NormalDist().inv_cdf(0.90)
    root_n = (
        z * math.sqrt(variance)
        + math.sqrt(z * z * variance + 4 * mean * threshold)
    ) / (2 * mean)
    return expected, math.ceil(root_n * root_n)


def main() -> None:
    composite = 0.49 * 0.48 / 0.52 + 0.51 * 0.52 / 0.52
    if not math.isclose(composite, 0.9623076923076923, abs_tol=1e-15):
        raise AssertionError("fixed composite-null replay disagrees")

    full_information = independent_mutual_information([[0.4, 0.1], [0.1, 0.4]])
    coarse_information = independent_mutual_information([[0.5, 0.5]])
    if not math.isclose(full_information, 0.19274475702175753, abs_tol=1e-15):
        raise AssertionError("fixed mutual-information replay disagrees")
    if not math.isclose(coarse_information, 0.0, abs_tol=1e-15):
        raise AssertionError("coarsened information should vanish")

    maximum_multiplier, maximum_excess = independent_property_replay()
    if not math.isclose(maximum_multiplier, 0.9839310968703472, abs_tol=1e-15):
        raise AssertionError("random composite-null replay disagrees")
    if maximum_excess > 1e-12:
        raise AssertionError("random data-processing replay failed")

    null_path = independent_binary_path(BASE_SEED, hidden_lift=False)
    lift_path = independent_binary_path(BASE_SEED + 1, hidden_lift=True)
    expected_null = (-32.4059215492, 1.17364005363)
    expected_lift = (26.9219896829, 28.3649956267)
    for observed, expected in zip(null_path, expected_null):
        if not math.isclose(observed, expected, abs_tol=5e-11):
            raise AssertionError("Born-null path replay disagrees")
    for observed, expected in zip(lift_path, expected_lift):
        if not math.isclose(observed, expected, abs_tol=5e-11):
            raise AssertionError("synthetic-lift path replay disagrees")

    expected_power = {
        0: (75_314, 119_635),
        8: (103_038, 153_191),
        16: (130_762, 186_030),
        32: (186_211, 250_321),
    }
    for code_bits, expected in expected_power.items():
        if independent_power_count(0.51, code_bits) != expected:
            raise AssertionError("prefix-code power replay disagrees")

    weights = [2**-2, 2**-3, 2**-3]
    if sum(weights) > 1:
        raise AssertionError("Kraft inequality failed")

    print("INDEPENDENT BORN-FRONTIER AUDIT: PASS")
    print(f"composite_multiplier,{composite:.12g}")
    print(f"full_information_nats,{full_information:.12g}")
    print(f"coarsened_information_nats,{coarse_information:.12g}")
    print(f"property_trials,{PROPERTY_TRIALS}")
    print(f"maximum_composite_multiplier,{maximum_multiplier:.12g}")
    print(f"maximum_data_processing_excess,{maximum_excess:.12g}")
    print(f"null_final_log_e,{null_path[0]:.12g}")
    print(f"null_max_log_e,{null_path[1]:.12g}")
    print(f"synthetic_lift_final_log_e,{lift_path[0]:.12g}")
    print(f"synthetic_lift_max_log_e,{lift_path[1]:.12g}")


if __name__ == "__main__":
    main()
