"""Coupled optical-source two-channel differential experiment, version 2.

Virtual lab only. Version 2 corrects version 1 without modifying it: force
and optical intervals are compared in one declared channel domain through a
bounded steady transfer, adversarial noise flips sign between phase labels,
and adversarial bounds and truth use each case actual balances. No physical
calibration or propulsion result is claimed.
"""

from dataclasses import replace
import hashlib
from itertools import product
import json
import math
from pathlib import Path
import sys

from differential_instrument import acquire as acquire_channels, tail_mean
from trial_detector import acquire_trial, analyse_trial
from virtual_acquisition import acquire as acquire_optical
from virtual_campaign import CONTROLS, expected_by_protocol, injected_contrast
from virtual_instruments import Balance

ROOT = Path(__file__).resolve().parent
SEEDS = 8
MAX_SEEDS = 8
SAMPLES = 100
STEP = 0.1
TAIL = 10
PHASE_JITTER = 0.01
FEED_VARIATION = 0.01
COMMON_FORCE = 40e-12
WEIGHT = 1.0
WEIGHT_UNCERTAINTY = 0.05
LEAKAGE = 0.05
LEAKAGE_KNOWLEDGE_BOUND = 0.01
CALIBRATION_KNOWLEDGE_BOUND = 0.005
REFERENCE_COMMON_COUPLING = 1.05
REFERENCE_HEAT_COUPLING = 1.05
TRANSFER_UNCERTAINTY = 0.02
MISMATCH_BOUND = 2e-12
PHASE_FORCE_SENSITIVITY = 50e-12
WAVELENGTH = 1.55e-6
SOURCE = {
    "wavelength_m": WAVELENGTH,
    "aperture_radius_m": 20*WAVELENGTH,
    "separation_m": 20*WAVELENGTH,
    "optical_feed_watts": 1.0,
    "laser_conversion_efficiency": 0.25,
    "control_power_watts": 0.1,
}
DETECTOR = {
    "cone_degrees": 2,
    "grid": (32, 64),
    "pointing_bound_degrees": 1e-4,
    "gain_bound": 1e-6,
    "total_power_bound_watts": 1e-6,
}
PRIMARY = Balance(1.0, 10.0, 5e-13, 5e-4, 5e-13, 5e-15, 5e-13, 2.0, 5e-13)
REFERENCE = Balance(1.5, 12.0, 6e-13, 6e-4, 7e-13, 6e-15, 7e-13, 2.0, 7e-13)
IMPLEMENTATION = (
    "coupled_differential_optical_v2.py", "differential_instrument.py",
    "virtual_acquisition.py", "trial_detector.py",
    "detector_qualification.py", "detector_stability.py",
    "virtual_campaign.py", "whole_acquisition.py",
    "virtual_instruments.py", "recoil_budget.py",
    "optical_driver.py", "optical_reference.py",
)


def _digest(name):
    path = ROOT / name
    if path.stat().st_size > 1048576:
        raise ValueError("revision input exceeds 1 MiB")
    return "sha256:"+hashlib.sha256(path.read_bytes()).hexdigest()


def _magnitude(interval):
    return 0 if interval[0] <= 0 <= interval[1] else min(abs(interval[0]),
                                                         abs(interval[1]))


def steady_transfer(primary, reference, weight=WEIGHT, leakage=LEAKAGE):
    """Infinite-time steady signal transfer of the difference readout."""
    return ((1+primary.calibration_fraction)
            - weight*leakage*(1+reference.calibration_fraction))


def transfer_interval(weight=WEIGHT, leakage=LEAKAGE,
                      primary_calibration=PRIMARY.calibration_fraction,
                      reference_calibration=REFERENCE.calibration_fraction,
                      weight_bound=WEIGHT_UNCERTAINTY,
                      leakage_bound=LEAKAGE_KNOWLEDGE_BOUND,
                      calibration_bound=CALIBRATION_KNOWLEDGE_BOUND):
    """Exact corner envelope of the steady transfer over declared knowledge.

    The transfer is affine in each variable separately, so extrema over the
    knowledge box occur at corners. All corners are evaluated; no sampling
    or nominal rescaling is involved.
    """
    values = []
    for gp, gr, w, leak in product(
            (primary_calibration-calibration_bound,
             primary_calibration+calibration_bound),
            (reference_calibration-calibration_bound,
             reference_calibration+calibration_bound),
            (weight-weight_bound, weight+weight_bound),
            (leakage-leakage_bound, leakage+leakage_bound)):
        values.append((1+gp)-w*leak*(1+gr))
    return [min(values), max(values)]


def map_interval(optical, transfer):
    """Interval product: predicted channel interval from raw optical."""
    products = [t*x for t in transfer for x in optical]
    return [min(products), max(products)]


TRANSFER_NOMINAL = steady_transfer(PRIMARY, REFERENCE)
TRANSFER_INTERVAL = transfer_interval()


def _optical_trials(seed, options, *, phase_jitter=PHASE_JITTER,
                    feed_variation=FEED_VARIATION):
    dummy = Balance(1.0, 1.0, 0, 0, 0, 0, 0, 0, 0)
    public, truth = acquire_optical(
        dummy, seed, **SOURCE, pairs=4, samples_per_trial=SAMPLES,
        step_seconds=STEP, phase_jitter_bound_radians=phase_jitter,
        feed_variation_bound_fraction=feed_variation,
        disclose_trial_sources=True, **options)
    if (len(public["trials"]) != 8
            or len(truth.get("source_trials", [])) != 8):
        raise ValueError("expected eight actual optical trials")
    return public["trials"], truth


def _trial_inputs(trial, source, options):
    label = trial["label"]
    orientation = options.get("orientation", 1)
    signal_enabled = options.get("signal_enabled", True)
    artefact = options.get("phase_correlated_force_newtons", 0)
    force = orientation*source["outgoing_radiation_recoil_component_newtons_xyz"][0]
    if not signal_enabled:
        force = 0.0
    force += (artefact if label == "A" else -artefact)
    return force, source["total_nonradiated_power_watts"]


def _trial_data(seed, options, *, primary=PRIMARY, reference=REFERENCE,
                phase_jitter=PHASE_JITTER, feed_variation=FEED_VARIATION,
                noise_mode="random", noise_modes=None):
    if noise_modes is not None:
        if (type(noise_modes) is not dict
                or set(noise_modes) != {"A", "B"}):
            raise ValueError("noise_modes must assign both phase labels")
    trials, optical_truth = _optical_trials(
        seed, options, phase_jitter=phase_jitter,
        feed_variation=feed_variation)
    sources = optical_truth["source_trials"]
    if len(sources) != len(trials):
        raise ValueError("optical labels and sources misaligned")
    continuation = None
    rows = []
    for index, (trial, injected) in enumerate(zip(trials, sources), 1):
        source = injected["source"]
        force, heat = _trial_inputs(trial, source, options)
        mode = (noise_modes[trial["label"]] if noise_modes is not None
                else noise_mode)
        difference = acquire_channels(
            primary, reference, [force]*SAMPLES, [COMMON_FORCE]*SAMPLES,
            [heat]*SAMPLES, STEP, seed*1000+index, weight=WEIGHT,
            leakage=LEAKAGE,
            reference_common_coupling=REFERENCE_COMMON_COUPLING,
            reference_heat_coupling=REFERENCE_HEAT_COUPLING,
            noise_mode=mode, initial=continuation)
        continuation = difference["continuation"]
        detector, _ = acquire_trial(
            phase_radians=source["phase_radians"],
            escaping_power_watts=source["escaping_radiated_power_watts"],
            end_seconds=injected["start_seconds"]+10,
            grid=DETECTOR["grid"], cone_degrees=DETECTOR["cone_degrees"],
            pointing_bound_degrees=DETECTOR["pointing_bound_degrees"],
            gain_bound=DETECTOR["gain_bound"],
            total_power_bound_watts=DETECTOR["total_power_bound_watts"],
            additive_error_watts=1e-5,
            gain_drift_per_second=1e-6,
            power_drift_watts_per_second=1e-6,
            wavelength_m=SOURCE["wavelength_m"],
            aperture_radius_m=SOURCE["aperture_radius_m"],
            separation_m=SOURCE["separation_m"])
        optical = analyse_trial(detector)
        if options.get("orientation", 1) == -1:
            optical = [-optical[1], -optical[0]]
        rows.append({
            "trial_id": trial["trial_id"],
            "label": trial["label"],
            "noise_mode": mode,
            "primary_tail_newtons": tail_mean(
                difference["primary_readings_newtons"], TAIL),
            "reference_tail_newtons": tail_mean(
                difference["reference_readings_newtons"], TAIL),
            "difference_tail_newtons": tail_mean(
                difference["difference_readings_newtons"], TAIL),
            "optical_interval_newtons": optical,
        })
    truth = {"balance": optical_truth}
    return rows, truth


def _force_interval(rows, phase_jitter, primary, reference):
    groups = {"A": [], "B": []}
    for row in rows:
        groups[row["label"]].append(row)
    if any(len(group) != 4 for group in groups.values()):
        raise ValueError("expected four complete A/B pairs")
    a, b = groups["A"], groups["B"]
    contrast = (math.fsum(row["difference_tail_newtons"] for row in b)/4
                - math.fsum(row["difference_tail_newtons"] for row in a)/4)
    max_reference = max(abs(row["reference_tail_newtons"])
                        for row in rows)
    max_primary = max(abs(row["primary_tail_newtons"]) for row in rows)
    per_phase = (
        primary.noise_bound_newtons
        + abs(WEIGHT)*reference.noise_bound_newtons
        + WEIGHT_UNCERTAINTY*max_reference
        + TRANSFER_UNCERTAINTY*max_primary
        + MISMATCH_BOUND
        + PHASE_FORCE_SENSITIVITY*phase_jitter)
    bound = 2*per_phase
    guard = 64*math.ulp(max(abs(contrast), bound))
    interval = [contrast-bound-guard, contrast+bound+guard]
    screen = ("resolved_label_contrast"
              if interval[0] > 0 or interval[1] < 0 else "unresolved")
    return contrast, interval, bound, screen


def _optical_interval(rows):
    groups = {"A": [], "B": []}
    for row in rows:
        groups[row["label"]].append(row["optical_interval_newtons"])
    if any(len(group) != 4 for group in groups.values()):
        raise ValueError("expected four complete optical pairs")
    a, b = groups["A"], groups["B"]
    predicted = [math.fsum(i[0] for i in b)/4-math.fsum(i[1] for i in a)/4,
                 math.fsum(i[1] for i in b)/4-math.fsum(i[0] for i in a)/4]
    guard = 64*math.ulp(max(abs(value) for value in predicted))
    return [predicted[0]-guard, predicted[1]+guard]


def _analyse(rows, truth, options, primary=PRIMARY, reference=REFERENCE,
             phase_jitter=PHASE_JITTER):
    contrast, force_interval, bound, screen = _force_interval(
        rows, phase_jitter, primary, reference)
    optical_raw = _optical_interval(rows)
    predicted_channel = map_interval(optical_raw, TRANSFER_INTERVAL)
    overlap = (max(force_interval[0], predicted_channel[0])
               <= min(force_interval[1], predicted_channel[1]))
    analysis = {
        "balance": {
            "screen": screen,
            "contrast_interval_newtons": force_interval,
            "label_b_minus_a_newtons": contrast,
        },
        "optical_contrast_interval_newtons": predicted_channel,
        "intervals_overlap": overlap,
    }
    raw_injected = injected_contrast(truth, options)
    actual_transfer = steady_transfer(primary, reference)
    channel_injected = raw_injected*actual_transfer
    return {
        "screen": screen,
        "force_contrast_newtons": contrast,
        "force_interval_newtons": force_interval,
        "force_bound_newtons": bound,
        "optical_interval_newtons": optical_raw,
        "predicted_channel_optical_interval_newtons": predicted_channel,
        "transfer_interval": TRANSFER_INTERVAL,
        "intervals_overlap": overlap,
        "expected_by_protocol": expected_by_protocol(options["_control"],
                                                     analysis),
        "truth_audit_contains_injected_contrast":
            force_interval[0] <= channel_injected <= force_interval[1],
        "raw_injected_contrast_newtons": raw_injected,
        "channel_injected_contrast_newtons": channel_injected,
        "declared_transfer": TRANSFER_NOMINAL,
        "actual_transfer": actual_transfer,
        "rows": rows,
    }


def _case(seed, control, options, **kwargs):
    primary = kwargs.get("primary", PRIMARY)
    reference = kwargs.get("reference", REFERENCE)
    rows, truth = _trial_data(seed, options, **kwargs)
    analysis = _analyse(rows, truth, {**options, "_control": control},
                        primary=primary, reference=reference,
                        phase_jitter=kwargs.get("phase_jitter", PHASE_JITTER))
    return analysis


def campaign(seeds=SEEDS):
    if type(seeds) is not int or not 1 <= seeds <= MAX_SEEDS:
        raise ValueError(f"seeds must be an integer from 1 to {MAX_SEEDS}")
    rows = []
    for seed in range(1, seeds+1):
        for control, options in CONTROLS:
            result = _case(seed, control, options)
            rows.append({
                "seed": seed,
                "control": control,
                **{key: result[key] for key in (
                    "screen", "force_contrast_newtons",
                    "force_interval_newtons", "force_bound_newtons",
                    "optical_interval_newtons",
                    "predicted_channel_optical_interval_newtons",
                    "transfer_interval", "intervals_overlap",
                    "expected_by_protocol",
                    "truth_audit_contains_injected_contrast",
                    "raw_injected_contrast_newtons",
                    "channel_injected_contrast_newtons",
                    "declared_transfer", "actual_transfer")},
                "trials": result["rows"],
            })
    summary = {}
    for control, _ in CONTROLS:
        group = [row for row in rows if row["control"] == control]
        summary[control] = {
            "matched": sum(row["expected_by_protocol"] for row in group),
            "truth_audit_contained": sum(
                row["truth_audit_contains_injected_contrast"]
                for row in group),
            "total": len(group),
        }
    all_controls = all(row["expected_by_protocol"] for row in rows)
    all_truth = all(row["truth_audit_contains_injected_contrast"]
                    for row in rows)
    optical_min = min(
        _magnitude(row["optical_interval_newtons"])
        for row in rows if row["control"] == "opposite-phase")
    return {
        "version": 2,
        "status": "virtual_lab_coupled_optical_differential_not_physical_evidence",
        "protocol": {
            "source": SOURCE,
            "detector": {**DETECTOR, "grid": list(DETECTOR["grid"])},
            "primary": PRIMARY.__dict__, "reference": REFERENCE.__dict__,
            "common_force_newtons": COMMON_FORCE,
            "weight": WEIGHT, "weight_uncertainty": WEIGHT_UNCERTAINTY,
            "leakage": LEAKAGE,
            "leakage_knowledge_bound": LEAKAGE_KNOWLEDGE_BOUND,
            "calibration_knowledge_bound": CALIBRATION_KNOWLEDGE_BOUND,
            "reference_common_coupling": REFERENCE_COMMON_COUPLING,
            "reference_heat_coupling": REFERENCE_HEAT_COUPLING,
            "transfer_uncertainty": TRANSFER_UNCERTAINTY,
            "mismatch_bound_newtons": MISMATCH_BOUND,
            "phase_force_sensitivity_newtons_per_radian":
                PHASE_FORCE_SENSITIVITY,
            "phase_jitter_bound_radians": PHASE_JITTER,
            "feed_variation_bound_fraction": FEED_VARIATION,
            "measurand": "channel_domain_b_minus_a_contrast_newtons",
            "steady_transfer_nominal": TRANSFER_NOMINAL,
            "steady_transfer_interval": TRANSFER_INTERVAL,
            "samples": SAMPLES, "step_seconds": STEP, "tail_samples": TAIL,
            "seeds": seeds, "controls": [control for control, _ in CONTROLS],
        },
        "implementation": {name: _digest(name) for name in IMPLEMENTATION},
        "primary": {
            "seeds": seeds, "controls": summary,
            "all_controls_matched": all_controls,
            "truth_audit_contained": sum(
                row["truth_audit_contains_injected_contrast"] for row in rows),
            "truth_audit_total": len(rows),
            "all_truth_contained": all_truth,
            "optical_minimum_newtons": optical_min,
            "outcome": ("virtual_lab_coupled_controls_consistent"
                        if all_controls and all_truth else
                        "virtual_lab_coupled_controls_inconsistent"),
            "rows": rows,
        },
        "adversarial": _adversarial(),
        "limits": {
            "acquisitions": seeds*len(CONTROLS),
            "trials": seeds*len(CONTROLS)*8,
            "samples_per_trial": SAMPLES,
            "output_bytes": 1048576,
            "network_calls": 0,
        },
        "warning": "Virtual lab only. Actual channel readouts under declared "
                   "assumed imperfections; no measured calibration, hardware "
                   "twin, physical recoil or control closure is established. "
                   "Finite seeded success is not a worst-case guarantee.",
    }


def _adversarial_entry(case, control, result, *, primary, reference,
                       noise, phase_jitter=PHASE_JITTER,
                       feed_variation=FEED_VARIATION):
    if control == "force-decoupled":
        rejected = (result["screen"] == "unresolved"
                    and not result["intervals_overlap"])
    else:
        rejected = None
    return {
        "case": case,
        "control": control,
        "primary": primary.__dict__,
        "reference": reference.__dict__,
        "noise_modes": noise,
        "phase_jitter_bound_radians": phase_jitter,
        "feed_variation_bound_fraction": feed_variation,
        "actual_transfer": result["actual_transfer"],
        "force_contrast_newtons": result["force_contrast_newtons"],
        "force_interval_newtons": result["force_interval_newtons"],
        "optical_interval_newtons": result["optical_interval_newtons"],
        "predicted_channel_optical_interval_newtons":
            result["predicted_channel_optical_interval_newtons"],
        "intervals_overlap": result["intervals_overlap"],
        "control_rejected": rejected,
        "truth_audit_contains_injected_contrast":
            result["truth_audit_contains_injected_contrast"],
    }


def _adversarial():
    cases = []
    flipped = {"A": "positive-extreme", "B": "negative-extreme"}
    result = _case(1, "force-decoupled", {"signal_enabled": False},
                   noise_modes=flipped)
    cases.append(_adversarial_entry(
        "opposing-noise-a-positive-b-negative", "force-decoupled", result,
        primary=PRIMARY, reference=REFERENCE, noise=flipped))
    flipped = {"A": "negative-extreme", "B": "positive-extreme"}
    result = _case(1, "force-decoupled", {"signal_enabled": False},
                   noise_modes=flipped)
    cases.append(_adversarial_entry(
        "opposing-noise-a-negative-b-positive", "force-decoupled", result,
        primary=PRIMARY, reference=REFERENCE, noise=flipped))
    result = _case(1, "force-decoupled", {"signal_enabled": False},
                   phase_jitter=0.05, feed_variation=0.05)
    cases.append(_adversarial_entry(
        "phase-feed-variation-5-percent", "force-decoupled", result,
        primary=PRIMARY, reference=REFERENCE, noise="random",
        phase_jitter=0.05, feed_variation=0.05))
    doubled = replace(REFERENCE, response_seconds=2*REFERENCE.response_seconds)
    result = _case(1, "force-decoupled", {"signal_enabled": False},
                   reference=doubled)
    cases.append(_adversarial_entry(
        "doubled-reference-response", "force-decoupled", result,
        primary=PRIMARY, reference=doubled, noise="random"))
    mismatched_primary = replace(PRIMARY, calibration_fraction=0.0105)
    mismatched_reference = replace(REFERENCE, calibration_fraction=-0.0094)
    result = _case(1, "force-decoupled", {"signal_enabled": False},
                   primary=mismatched_primary, reference=mismatched_reference)
    cases.append(_adversarial_entry(
        "calibration-mismatch-decoupled", "force-decoupled", result,
        primary=mismatched_primary, reference=mismatched_reference,
        noise="random"))
    result = _case(1, "opposite-phase", {},
                   primary=mismatched_primary, reference=mismatched_reference)
    cases.append(_adversarial_entry(
        "calibration-mismatch-signal", "opposite-phase", result,
        primary=mismatched_primary, reference=mismatched_reference,
        noise="random"))
    return cases


def main():
    arguments = sys.argv[1:]
    seeds = SEEDS
    if arguments:
        if len(arguments) != 2 or arguments[0] != "--seeds":
            raise SystemExit("usage: coupled_differential_optical_v2.py [--seeds N]")
        token = arguments[1]
        if (not token.isascii() or not token.isdecimal()
                or len(token) > 1):
            raise SystemExit("seed count must be one ASCII digit")
        seeds = int(token)
        if not 1 <= seeds <= MAX_SEEDS:
            raise SystemExit(f"seed count must be from 1 to {MAX_SEEDS}")
    payload = json.dumps(campaign(seeds=seeds), sort_keys=True,
                         separators=(",", ":"), allow_nan=False)
    if len(payload.encode("utf-8")) > 1048576:
        raise SystemExit("coupled differential output exceeds 1 MiB")
    print(payload)


if __name__ == "__main__":
    main()
