"""Explicit two-channel virtual force instrument, not measured equipment."""

import math
import random
from dataclasses import replace

from recoil_budget import bounded
from virtual_instruments import Balance, MAX_SAMPLES, observe


def acquire(primary, reference, signal, common, heat, step, seed, *,
            weight=1, leakage=0, reference_common_coupling=1,
            reference_heat_coupling=1, noise_mode="random", initial=None):
    """Read both channels, then subtract; never shrink an asserted error bound.

    Calibration/response act on signal and disturbances alike. Independent
    readout noise is added after the real channel responses. Extrema are
    deterministic stress inputs inside each channel's declared noise bound.
    """
    if type(primary) is not Balance or type(reference) is not Balance:
        raise ValueError("two declared Balance channels required")
    primary.validate()
    reference.validate()
    if (type(seed) is not int or not 0 <= seed <= 2**32-1):
        raise ValueError("seed must be unsigned 32-bit integer")
    dt = bounded(step, 0.001, 10, "sample step")
    w = bounded(weight, -2, 2, "subtraction weight")
    leak = bounded(leakage, 0, 1, "reference signal leakage")
    coupling = bounded(reference_common_coupling, 0, 2, "reference disturbance coupling")
    heat_coupling = bounded(reference_heat_coupling, 0, 2, "reference heat coupling")
    if type(noise_mode) is not str or noise_mode not in ("random", "positive-extreme", "negative-extreme"):
        raise ValueError("unsupported noise mode")
    if (any(type(values) is not list for values in (signal, common, heat))
            or not 1 <= len(signal) <= MAX_SAMPLES
            or len(signal) != len(common) or len(signal) != len(heat)):
        raise ValueError("matched bounded sample lists required")
    signal = [bounded(x, -1e-3, 1e-3, "signal force") for x in signal]
    common = [bounded(x, -1e-3, 1e-3, "common force") for x in common]
    heat = [bounded(x, 0, 100, "shared heat") for x in heat]
    forces_a = [bounded(s+c, -1e-3, 1e-3, "primary force") for s, c in zip(signal, common)]
    forces_b = [bounded(leak*s+coupling*c, -1e-3, 1e-3, "reference force") for s, c in zip(signal, common)]
    heat_b = [bounded(heat_coupling*h, 0, 100, "reference heat") for h in heat]
    if initial is None:
        states = [{"mechanical_newtons": 0, "thermal_newtons": 0, "elapsed_seconds": 0}
                  for _ in range(2)]
    else:
        if type(initial) is not list or len(initial) != 2:
            raise ValueError("two explicit continuation states required")
        states = initial
    for state in states:
        if type(state) is not dict or set(state) != {"mechanical_newtons", "thermal_newtons", "elapsed_seconds"}:
            raise ValueError("unsupported continuation state")
        bounded(state["mechanical_newtons"], -1e-3, 1e-3, "mechanical state")
        bounded(state["thermal_newtons"], -1e-3, 1e-3, "thermal state")
        start = bounded(state["elapsed_seconds"], 0, 3600, "elapsed time")
        if start+len(signal)*dt > 3600:
            raise ValueError("acquisition exceeds one hour")
    if states[0]["elapsed_seconds"] != states[1]["elapsed_seconds"]:
        raise ValueError("channel clocks must align")
    if any(balance.vibration_hertz > 0.5/dt for balance in (primary, reference)):
        raise ValueError("vibration exceeds sample Nyquist frequency")
    # Preflight is complete before either numerical channel executes.
    rng = random.Random(seed)
    readings, continuation = [], []
    for balance, force, heating, state in zip((primary, reference),
            (forces_a, forces_b), (heat, heat_b), states):
        # Noise belongs to each readout, not to the mechanical input.
        quiet = replace(balance, noise_bound_newtons=0)
        result = observe(quiet, force, heating, dt, 0,
                         initial_force_newtons=state["mechanical_newtons"],
                         initial_thermal_newtons=state["thermal_newtons"],
                         start_seconds=state["elapsed_seconds"])
        channel_rng = random.Random(rng.randrange(2**32))
        index = len(readings)
        noise = balance.noise_bound_newtons
        if noise_mode == "random":
            values = [v+channel_rng.uniform(-noise, noise) for v in result["readings_newtons"]]
        else:
            direction = 1 if noise_mode == "positive-extreme" else -1
            sign = direction if index == 0 else -direction*(1 if w >= 0 else -1)
            values = [v+sign*noise for v in result["readings_newtons"]]
        readings.append(values)
        continuation.append(result["continuation_state"])
    return {"status": "virtual_two_channel_readout_not_physical_evidence",
            "primary_readings_newtons": readings[0],
            "reference_readings_newtons": readings[1],
            "difference_readings_newtons": [a-w*b for a, b in zip(*readings)],
            "difference_noise_bound_newtons": primary.noise_bound_newtons+abs(w)*reference.noise_bound_newtons,
            "steady_signal_transfer": (1+primary.calibration_fraction)-w*leak*(1+reference.calibration_fraction),
            "sample_step_seconds": dt,
            "continuation": continuation}


def tail_mean(values, count=10):
    if type(values) is not list or not 1 <= len(values) <= MAX_SAMPLES:
        raise ValueError("bounded reading list required")
    if type(count) is not int or not 1 <= count <= len(values):
        raise ValueError("invalid tail count")
    return math.fsum(bounded(x, -1, 1, "reading") for x in values[-count:])/count
