"""ArcSecs environmental snapshots; no motor control. Optional second USB board."""
import math,time,datetime
from decimal import Decimal
FIELDS=['temperature_C','motor_voltage_V','motor_current_A']
def parse_sensor(line):
    p=line.strip().split(',')
    if len(p)!=4 or p[0]!='ENV': raise ValueError('Expected ENV,temp_C,voltage_V,current_A')
    v=[float(x) for x in p[1:]]
    if not all(math.isfinite(x) for x in v): raise ValueError('Nonfinite sensor value')
    if not (-40<=v[0]<=125 and 0<=v[1]<=26 and abs(v[2])<=3.2): raise ValueError('Outside provisional sensor range')
    return dict(zip(FIELDS,v))
def snapshot(port):
    import serial
    with serial.Serial(port,115200,timeout=.25) as s:
        time.sleep(2);s.reset_input_buffer();s.write(b'Q');s.flush()
        deadline=time.monotonic()+4
        while time.monotonic()<deadline:
            line=s.readline().decode('ascii',errors='replace').strip()
            if line.startswith('ENV,'):return parse_sensor(line)
            if line.startswith('ERR,'):raise RuntimeError(line)
        raise RuntimeError('No environmental snapshot')
def safe_snapshot(mode,port,synthetic):
    stamp=datetime.datetime.now(datetime.timezone.utc).isoformat()
    try:
        v=parse_sensor(synthetic) if mode=='simulation' else snapshot(port) if port else None
        return {'utc':stamp,'status':'ok' if v else 'not_connected',**(v or {})}
    except Exception as e:return {'utc':stamp,'status':'error','detail':str(e)}
