"""Multi-scenario virtual PF-002 campaign; simulated evidence only.

The campaign sweeps declared apparatus assumptions and blind controls through
the coupled virtual acquisition. It does not measure a physical instrument,
validate the simulator against reality, or assign a canonical PF-002 result.
"""

import json
import math
import sys
from dataclasses import dataclass

from virtual_instruments import Balance
from whole_acquisition import acquire, analyse, apparatus_bound
from recoil_budget import bounded

MAX_SEEDS = 8
DEFAULT_SEEDS = 4


@dataclass(frozen=True)
class Scenario:
    """One declared balance assumption set, not a measured instrument class."""

    name: str
    balance: Balance
    note: str


# The parameter ladder is hypothetical. It exists to expose where the coupled
# analysis stops separating the signal from its controls, not to predict a lab.
SCENARIOS = (
    Scenario(
        "idealised",
        Balance(0.1, 2, 0, 0, 0, 0, 0, 0, 1e-13),
        "Existing idealised qualification balance; no thermal, calibration or "
        "drift terms and a 0.1 pN read-noise bound.",
    ),
    Scenario(
        "bench",
        Balance(0.5, 5, 1e-13, 1e-4, 1e-13, 1e-15, 1e-13, 1.0, 1e-13),
        "Hypothetical bench-grade terms: 0.1 pN thermal, 0.01 percent calibration, "
        "1 pN offset, 1 fN/s drift and 0.1 pN vibration and noise.",
    ),
    Scenario(
        "field",
        Balance(1.0, 10, 5e-13, 5e-4, 5e-13, 5e-15, 5e-13, 2.0, 5e-13),
        "Hypothetical field-grade terms five times the bench case; the "
        "force-decoupled control is expected to become consistent.",
    ),
    Scenario(
        "adverse",
        Balance(1.0, 10, 1e-12, 1e-3, 1e-12, 1e-14, 1e-12, 2.0, 1e-12),
        "Hypothetical adverse terms at the piconewton scale; the phase signal "
        "is expected to become unresolved.",
    ),
)

CONTROLS = (
    ("opposite-phase", {}),
    ("phase-null", {"null": True}),
    ("force-decoupled", {"signal_enabled": False}),
    ("orientation-reversed", {"orientation": -1}),
    ("impostor", {"signal_enabled": False,
                  "phase_correlated_force_newtons": 1e-9}),
)

FIDELITY = {
    "version": "virtual-pf002-fidelity-v1",
    "modelled": [
        "prescribed 1550 nm two-aperture far-field wavefront and passive two-port feed",
        "phase-dependent escaping and absorbed power, recoil and internal heat",
        "trial-constant phase and feed variation across eight ten-second trials",
        "first-order balance response, thermal lag, offset, linear drift, "
        "sinusoidal vibration and bounded read noise",
        "finite 8 by 32 integrated detector pixels with gain and power drift, "
        "total-power bound and additive dark error",
        "seeded blind labels, continuous carry-over and post-analysis truth separation",
        "conservative interval analysis without averaging gain or shared-error cancellation",
    ],
    "not_modelled": [
        "real optical apertures, materials, splitter, driver impedance, "
        "near-field forces and incoming momentum",
        "within-trial phase noise, mode hopping, polarisation drift and source spectrum",
        "detector saturation, dark-current spectrum, readout nonlinearity, "
        "lens mapping and stray light",
        "measured balance noise spectrum, cable forces, support creep, acoustic "
        "and electromagnetic pickup",
        "thermal radiation anisotropy and the direction in which heat leaves "
        "the apparatus",
        "environmental temperature, pressure, humidity and facility vibration",
        "independent replication, operator procedure and hardware safety",
    ],
    "claim": "A declared simulation, not a physical lab or hardware validation. "
             "Omitted effects can dominate the piconewton signal; this ledger is "
             "an audit of assumptions, not evidence of representativeness.",
}


def injected_contrast(truth, options):
    """Post-analysis audit value; never an input to the blind analyser."""
    if (type(truth) is not dict or type(truth.get("balance")) is not dict
            or type(truth["balance"].get("sources")) is not list):
        raise ValueError("expected simulation truth with sources")
    trials = truth["balance"].get("source_trials")
    labels = truth["balance"].get("acquisition_order")
    if (type(trials) is not list or type(labels) is not list
            or len(trials) != 8 or len(labels) != 8
            or labels.count("A") != 4 or labels.count("B") != 4):
        raise ValueError("expected complete actual trial injections")
    orientation = options.get("orientation", 1)
    signal_enabled = options.get("signal_enabled", True)
    artefact = options.get("phase_correlated_force_newtons", 0)
    if (type(orientation) is not int or orientation not in (-1, 1)
            or type(signal_enabled) is not bool
            or type(artefact) not in (int, float) or not -1e-9 <= artefact <= 1e-9):
        raise ValueError("unsupported control options")
    forces = {"A": [], "B": []}
    for index, (label, trial) in enumerate(zip(labels, trials), 1):
        if (type(trial) is not dict or trial.get("trial_id") != f"T{index:03d}"
                or type(trial.get("source")) is not dict):
            raise ValueError("missing or reordered actual trial injection")
        vector = trial["source"].get("outgoing_radiation_recoil_component_newtons_xyz")
        if type(vector) is not list or len(vector) != 3:
            raise ValueError("missing actual recoil vector")
        force = orientation*bounded(vector[0], -1, 1, "actual injected recoil")
        if not signal_enabled:
            force = 0
        forces[label].append(force+(artefact if label == "A" else -artefact))
    return math.fsum(forces["B"])/4-math.fsum(forces["A"])/4


def expected_by_protocol(control, analysis):
    """Declared design expectation, not a scientific acceptance rule."""
    screen = analysis["balance"]["screen"]
    overlap = analysis["intervals_overlap"]
    if control in ("opposite-phase", "orientation-reversed"):
        return screen == "resolved_label_contrast" and overlap is True
    if control == "phase-null":
        return screen == "unresolved" and overlap is True
    if control == "force-decoupled":
        return screen == "unresolved" and overlap is False
    if control == "impostor":
        return screen == "resolved_label_contrast" and overlap is False
    raise ValueError("unsupported control")


def _summarise(rows):
    summary = {}
    for control, _ in CONTROLS:
        group = [row for row in rows if row["control"] == control]
        summary[control] = {
            "matches_protocol": 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),
        }
    return summary


def _magnitude(interval):
    """Smallest absolute value the interval permits; zero if it spans zero."""
    return 0 if interval[0] <= 0 <= interval[1] else min(abs(interval[0]), abs(interval[1]))


def _design_margins(rows, bound):
    """Separate signal-resolution and control-rejection requirements.

    A force-decoupled control is rejected only when the balance bound is below
    the optical interval's smallest magnitude. That requirement can be much
    tighter than the signal-resolution requirement, so report both.
    """
    opposite = [row for row in rows if row["control"] == "opposite-phase"]
    optical = min(_magnitude(row["optical_interval_newtons"])
                  for row in opposite)
    signal = min(abs(row["label_contrast_newtons"]) for row in opposite)
    return {
        "apparatus_bound_newtons": bound,
        "minimum_optical_interval_magnitude_newtons": optical,
        "minimum_label_contrast_magnitude_newtons": signal,
        "force_decoupled_rejection_margin_newtons": optical-bound,
        "signal_resolution_margin_newtons": signal-bound,
    }


def run_campaign(*, seeds=DEFAULT_SEEDS):
    """Run the frozen scenario ladder over fixed seeds; no file or network I/O."""
    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}")
    scenarios = []
    for scenario in SCENARIOS:
        bound = apparatus_bound(scenario.balance)
        rows = []
        for seed in range(1, seeds+1):
            for control, options in CONTROLS:
                public, truth = acquire(scenario.balance, seed, **options)
                analysis = analyse(public,
                                   differential_error_bound_newtons=bound)
                low, high = analysis["balance"]["contrast_interval_newtons"]
                injected = injected_contrast(truth, options)
                rows.append({
                    "seed": seed,
                    "control": control,
                    "screen": analysis["balance"]["screen"],
                    "intervals_overlap": analysis["intervals_overlap"],
                    "expected_by_protocol": expected_by_protocol(control, analysis),
                    "truth_audit_contains_injected_contrast":
                        low <= injected <= high,
                    "balance_interval_newtons": [low, high],
                    "optical_interval_newtons":
                        analysis["optical_contrast_interval_newtons"],
                    "label_contrast_newtons":
                        analysis["balance"]["label_b_minus_a_newtons"],
                })
        scenarios.append({
            "name": scenario.name,
            "note": scenario.note,
            "apparatus_bound_newtons": bound,
            "summary": _summarise(rows),
            "design_margins": _design_margins(rows, bound),
            "rows": rows,
        })
    acquisitions = len(SCENARIOS)*seeds*len(CONTROLS)
    return {
        "status": "simulated_virtual_pf002_campaign_not_physical_evidence",
        "models": {
            "balance": "first_order_endpoint_thermal_cascade_v1",
            "acquisition": "cold_carryover_seeded_balanced_pairs_v1",
            "detector": "finite_integrated_pixel_trial_age_v1",
            "analysis": "paired_tail_mean_absolute_error_interval_v1",
        },
        "frozen_protocol": {
            "scenarios": [scenario.name for scenario in SCENARIOS],
            "controls": [control for control, _ in CONTROLS],
            "seeds": seeds,
            "seed_range": [1, seeds],
            "trials_per_acquisition": 8,
            "trial_seconds": 10,
            "source_geometry": "1550nm_wavefront_radius_and_separation_31um",
            "optical_feed_watts": 1,
            "laser_efficiency": 0.25,
            "control_watts": 0.1,
            "phase_jitter_bound_radians": 0.01,
            "feed_variation_bound_fraction": 0.01,
            "detector_grid": [8, 32],
            "interpretation": "Design sweep under declared assumptions; not a "
                              "physical result, hardware specification or "
                              "canonical PF-002 record.",
        },
        "scenarios": scenarios,
        "fidelity": FIDELITY,
        "limits": {
            "acquisitions": acquisitions,
            "balance_samples_per_acquisition": 800,
            "detector_pixels_per_acquisition": 8*32,
            "network_calls": 0,
            "output_bytes": 65536,
        },
        "warning": "Simulated readings and hypothetical balance classes only. "
                   "A protocol match does not establish physical recoil, and a "
                   "mismatch does not disprove it. Omitted physics remains the "
                   "dominant uncertainty until measured calibration exists.",
    }


def main():
    arguments = sys.argv[1:]
    seeds = DEFAULT_SEEDS
    if arguments:
        if len(arguments) != 2 or arguments[0] != "--seeds":
            raise SystemExit("usage: virtual_campaign.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(run_campaign(seeds=seeds), sort_keys=True,
                         separators=(",", ":"), allow_nan=False)
    if len(payload.encode("utf-8")) > 65536:
        raise SystemExit("virtual campaign output exceeds 64 KiB")
    print(payload)


if __name__ == "__main__":
    main()
