"""Synthetic instruments for design qualification, never hardware measurements.

Force and thermal channels use exact zero-order-hold first-order updates.
Noise is bounded uniform synthetic noise, not a measured spectral density.
"""

import math
import random
from dataclasses import dataclass

from recoil_budget import bounded

MAX_SAMPLES = 4096


@dataclass(frozen=True)
class Balance:
    response_seconds: float
    thermal_seconds: float
    thermal_newtons_per_watt: float
    calibration_fraction: float
    offset_newtons: float
    drift_newtons_per_second: float
    vibration_newtons: float
    vibration_hertz: float
    noise_bound_newtons: float

    def validate(self):
        bounds = {
            "response_seconds": (1e-3, 1000),
            "thermal_seconds": (1e-3, 10000),
            "thermal_newtons_per_watt": (-1e-6, 1e-6),
            "calibration_fraction": (-0.5, 0.5),
            "offset_newtons": (-1e-3, 1e-3),
            "drift_newtons_per_second": (-1e-6, 1e-6),
            "vibration_newtons": (0, 1e-3),
            "vibration_hertz": (0, 100),
            "noise_bound_newtons": (0, 1e-3),
        }
        for name, (lower, upper) in bounds.items():
            bounded(getattr(self, name), lower, upper, name)


def observe(balance: Balance, force_newtons: list[float], heat_watts: list[float],
            step_seconds: float, seed: int, *, initial_force_newtons=0,
            initial_thermal_newtons=0, start_seconds=0) -> dict:
    """Return readings and private continuation states for acquisition use.

    Each input is constant during its time bin; readings are at bin endpoints.
    Initial states are explicit, so settled and cold-start runs cannot be mixed.
    Thermal coupling represents an assumed nuisance, not thermodynamic proof.
    Offset/drift/vibration/noise are readout terms after the response filter.
    """
    if not isinstance(balance, Balance):
        raise ValueError("expected a Balance instrument configuration")
    balance.validate()
    step = bounded(step_seconds, 1e-3, 10, "sample step")
    if (type(seed) is not int or not 0 <= seed <= 2**32-1):
        raise ValueError("seed must be an unsigned 32-bit integer")
    if (type(force_newtons) is not list or type(heat_watts) is not list
            or not 1 <= len(force_newtons) <= MAX_SAMPLES
            or len(force_newtons) != len(heat_watts)):
        raise ValueError("matched force/heat lists need 1 to 4096 samples")
    start = bounded(start_seconds, 0, 3600, "acquisition start time")
    if start+len(force_newtons)*step > 3600:
        raise ValueError("synthetic acquisition exceeds one hour")
    if balance.vibration_hertz > 0.5/step:
        raise ValueError("vibration exceeds the sample Nyquist frequency")
    force = [bounded(x, -1e-3, 1e-3, "input force") for x in force_newtons]
    heat = [bounded(x, 0, 100, "nonradiated power") for x in heat_watts]
    mechanical = bounded(initial_force_newtons, -1e-3, 1e-3, "initial force")
    thermal = bounded(initial_thermal_newtons, -1e-3, 1e-3, "initial thermal force")
    response_weight = -math.expm1(-step/balance.response_seconds)
    thermal_weight = -math.expm1(-step/balance.thermal_seconds)
    rng = random.Random(seed)
    readings = []
    for index, (input_force, input_heat) in enumerate(zip(force, heat)):
        thermal += thermal_weight*(input_heat*balance.thermal_newtons_per_watt-thermal)
        # Thermal target is taken at the bin endpoint, then held over the
        # mechanical update. This is an explicitly discretised cascade, not
        # the exact continuous coupled solution; step refinement must qualify it.
        mechanical += response_weight*(input_force+thermal-mechanical)
        time = start+(index+1)*step
        reading = ((1+balance.calibration_fraction)*mechanical
                   + balance.offset_newtons + time*balance.drift_newtons_per_second
                   + balance.vibration_newtons*math.sin(2*math.pi*balance.vibration_hertz*time)
                   + rng.uniform(-balance.noise_bound_newtons, balance.noise_bound_newtons))
        readings.append(reading)
    return {
        "status": "synthetic_instrument_readings_not_physical_evidence",
        "model": "first_order_endpoint_thermal_cascade_v1",
        "sample_step_seconds": step,
        "sample_count": len(readings),
        "readings_newtons": readings,
        "continuation_state": {"mechanical_newtons": mechanical,
                               "thermal_newtons": thermal,
                               "elapsed_seconds": start+len(readings)*step},
    }
