#!/usr/bin/env python3
"""
Kiran Live Classifier v0.7.0
Sensors -> 106 features -> v0.7.0 Ensemble (stdio) -> Gate Chain -> State

Reads 4 sensors at 4Hz, accumulates 30-second windows, extracts 106 features,
pipes to persistent C stdio bridge engine, displays real-time classification.
"""

import json
import math
import subprocess
import sys
import time
import logging
from datetime import datetime, timezone
from pathlib import Path

import numpy as np

try:
    import board
    import busio
    import adafruit_mpu6050
    import adafruit_bh1750
    import adafruit_ads1x15.ads1115 as ADS
    from adafruit_ads1x15.analog_in import AnalogIn
    HAS_SENSORS = True
except ImportError:
    HAS_SENSORS = False

try:
    import qwiic_max3010x
    HAS_MAX30102 = True
except ImportError:
    HAS_MAX30102 = False

try:
    from kiran_gates import KiranGateChain
    HAS_GATE_CHAIN = True
except ImportError:
    HAS_GATE_CHAIN = False

try:
    _nlm_root = Path.home() / "NLM" / "bodi-biocare"
    if _nlm_root.exists():
        sys.path.insert(0, str(_nlm_root))
    from kiran.attestation import attest_decision
    HAS_ATTESTATION = True
except ImportError:
    HAS_ATTESTATION = False

# C engine path for v0.7.0 stdio bridge
C_ENGINE = Path(__file__).parent / "kiran_ensemble_stdio"
C_ENGINE_FALLBACK = Path(__file__).parent / "kiran_ensemble_stdin"
SAMPLE_RATE = 4
WINDOW_SIZE = 120  # 30 seconds at 4Hz
SLIDE_STEP = 40    # 10-second slide

FEATURE_ORDER = [
    "eda_mean", "eda_std", "eda_min", "eda_max", "eda_range", "eda_median",
    "eda_skew", "eda_kurtosis", "eda_slope", "eda_slope_std", "eda_n_peaks",
    "eda_iqr", "eda_scr_mean", "eda_scr_max", "eda_tonic_mean",
    "hr_mean", "hr_std", "hr_min", "hr_max", "hr_range", "hr_median",
    "hr_skew", "hr_kurtosis", "hr_slope", "hr_slope_std", "hr_n_peaks",
    "hr_iqr", "hr_rmssd", "hr_sdnn", "hr_pnn50", "hr_pnn20",
    "temp_mean", "temp_std", "temp_min", "temp_max", "temp_range", "temp_median",
    "temp_skew", "temp_kurtosis", "temp_slope", "temp_slope_std", "temp_n_peaks",
    "temp_iqr", "temp_trend",
    "bvp_mean", "bvp_std", "bvp_min", "bvp_max", "bvp_range", "bvp_median",
    "bvp_skew", "bvp_kurtosis", "bvp_slope", "bvp_slope_std", "bvp_n_peaks",
    "bvp_iqr",
    "acc_x_mean", "acc_x_std", "acc_x_min", "acc_x_max", "acc_x_range",
    "acc_x_median", "acc_x_skew", "acc_x_kurtosis", "acc_x_slope",
    "acc_x_slope_std", "acc_x_n_peaks", "acc_x_iqr",
    "acc_y_mean", "acc_y_std", "acc_y_min", "acc_y_max", "acc_y_range",
    "acc_y_median", "acc_y_skew", "acc_y_kurtosis", "acc_y_slope",
    "acc_y_slope_std", "acc_y_n_peaks", "acc_y_iqr",
    "acc_z_mean", "acc_z_std", "acc_z_min", "acc_z_max", "acc_z_range",
    "acc_z_median", "acc_z_skew", "acc_z_kurtosis", "acc_z_slope",
    "acc_z_slope_std", "acc_z_n_peaks", "acc_z_iqr",
    "acc_mag_mean", "acc_mag_std", "acc_mag_min", "acc_mag_max", "acc_mag_range",
    "acc_mag_median", "acc_mag_skew", "acc_mag_kurtosis", "acc_mag_slope",
    "acc_mag_slope_std", "acc_mag_n_peaks", "acc_mag_iqr",
    "acc_jerk_mean", "acc_jerk_max",
]

# Logging setup
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("kiran")


def safe_skew(a):
    n = len(a)
    if n < 3:
        return 0.0
    m = np.mean(a)
    s = np.std(a)
    if s == 0:
        return 0.0
    return float(np.mean(((a - m) / s) ** 3))


def safe_kurtosis(a):
    n = len(a)
    if n < 4:
        return 0.0
    m = np.mean(a)
    s = np.std(a)
    if s == 0:
        return 0.0
    return float(np.mean(((a - m) / s) ** 4) - 3.0)


def window_stats(w, prefix):
    f = {}
    f[f"{prefix}_mean"] = float(np.mean(w))
    f[f"{prefix}_std"] = float(np.std(w))
    f[f"{prefix}_min"] = float(np.min(w))
    f[f"{prefix}_max"] = float(np.max(w))
    f[f"{prefix}_range"] = float(np.ptp(w))
    f[f"{prefix}_median"] = float(np.median(w))
    f[f"{prefix}_skew"] = safe_skew(w)
    f[f"{prefix}_kurtosis"] = safe_kurtosis(w)
    if len(w) > 1:
        d = np.diff(w)
        f[f"{prefix}_slope"] = float(np.mean(d))
        f[f"{prefix}_slope_std"] = float(np.std(d))
        peaks = int(np.sum((d[:-1] > 0) & (d[1:] < 0))) if len(d) > 1 else 0
        f[f"{prefix}_n_peaks"] = float(peaks)
    else:
        f[f"{prefix}_slope"] = 0.0
        f[f"{prefix}_slope_std"] = 0.0
        f[f"{prefix}_n_peaks"] = 0.0
    q25, q75 = np.percentile(w, [25, 75])
    f[f"{prefix}_iqr"] = float(q75 - q25)
    return f


def extract_features(eda, hr, temp, bvp, acc_x, acc_y, acc_z):
    feats = {}

    feats.update(window_stats(eda, "eda"))
    if len(eda) > 10:
        ks = min(len(eda) // 4, 50)
        if ks > 0:
            tonic = np.convolve(eda, np.ones(ks) / ks, mode="same")
            phasic = eda - tonic
            feats["eda_scr_mean"] = float(np.mean(np.abs(phasic)))
            feats["eda_scr_max"] = float(np.max(np.abs(phasic)))
            feats["eda_tonic_mean"] = float(np.mean(tonic))
        else:
            feats["eda_scr_mean"] = 0.0
            feats["eda_scr_max"] = 0.0
            feats["eda_tonic_mean"] = float(np.mean(eda))
    else:
        feats["eda_scr_mean"] = 0.0
        feats["eda_scr_max"] = 0.0
        feats["eda_tonic_mean"] = float(np.mean(eda))

    feats.update(window_stats(hr, "hr"))
    if len(hr) > 4:
        diffs = np.diff(hr)
        feats["hr_rmssd"] = float(np.sqrt(np.mean(diffs ** 2)))
        feats["hr_sdnn"] = float(np.std(hr))
        sd = np.abs(np.diff(diffs))
        feats["hr_pnn50"] = float(np.sum(sd > 50) / max(len(sd), 1))
        feats["hr_pnn20"] = float(np.sum(sd > 20) / max(len(sd), 1))
    else:
        feats["hr_rmssd"] = 0.0
        feats["hr_sdnn"] = 0.0
        feats["hr_pnn50"] = 0.0
        feats["hr_pnn20"] = 0.0

    feats.update(window_stats(temp, "temp"))
    if len(temp) > 2:
        feats["temp_trend"] = float(np.polyfit(np.arange(len(temp)), temp, 1)[0])
    else:
        feats["temp_trend"] = 0.0

    feats.update(window_stats(bvp, "bvp"))

    for axis, name in [(acc_x, "acc_x"), (acc_y, "acc_y"), (acc_z, "acc_z")]:
        feats.update(window_stats(axis, name))

    mag = np.sqrt(acc_x ** 2 + acc_y ** 2 + acc_z ** 2)
    feats.update(window_stats(mag, "acc_mag"))
    if len(mag) > 1:
        jerk = np.diff(mag)
        feats["acc_jerk_mean"] = float(np.mean(np.abs(jerk)))
        feats["acc_jerk_max"] = float(np.max(np.abs(jerk)))
    else:
        feats["acc_jerk_mean"] = 0.0
        feats["acc_jerk_max"] = 0.0

    return feats


def _estimate_hr(bvp_buf, sample_rate):
    if len(bvp_buf) < sample_rate * 5:
        return 72.0
    recent = np.array(bvp_buf[-(sample_rate * 10):])
    if np.std(recent) < 1e-6:
        return 72.0
    d = np.diff(recent)
    if len(d) < 3:
        return 72.0
    peaks = np.sum((d[:-1] > 0) & (d[1:] < 0))
    duration_sec = len(recent) / sample_rate
    if duration_sec < 1:
        return 72.0
    bpm = (peaks / duration_sec) * 60.0
    return min(max(bpm, 40.0), 200.0)


def features_to_csv(feats):
    return ",".join(str(feats.get(name, 0.0)) for name in FEATURE_ORDER)


def classify_with_ensemble_stdio(csv_line, proc, ensemble=True):
    """
    Send 106 CSV features to the persistent C stdio bridge,
    read one JSON line from stdout, parse KiranResult.
    Uses stdin.write/stdout.readline for persistent subprocess (not communicate).
    """
    proc.stdin.write((csv_line + "\n").encode())
    proc.stdin.flush()
    output = proc.stdout.readline().decode().strip()

    if not output:
        # Empty response -- treat as CALM
        return {
            "state": "CALM",
            "confidence": 1.0,
            "p_stress": 0.0,
            "p_exercise": 0.0,
            "p_fall": 0.0,
            "calm_probs": [0.0, 0.0, 0.0],
            "p_short": 0.0,
            "p_medium": 0.0,
            "p_long": 0.0,
            "p_ensemble": 0.0,
        }

    # Parse JSON result from the C bridge
    try:
        data = json.loads(output)
    except json.JSONDecodeError:
        logger.warning("Failed to parse C engine output: %s", output)
        return {
            "state": "CALM",
            "confidence": 1.0,
            "p_stress": 0.0,
            "p_exercise": 0.0,
            "p_fall": 0.0,
            "calm_probs": [0.0, 0.0, 0.0],
            "p_short": 0.0,
            "p_medium": 0.0,
            "p_long": 0.0,
            "p_ensemble": 0.0,
        }

    p_short = float(data.get("p_short", 0.0))
    p_medium = float(data.get("p_medium", 0.0))
    p_long = float(data.get("p_long", 0.0))
    p_ensemble = float(data.get("p_ensemble", 0.0))
    prediction = int(data.get("prediction", 0))

    # Map v0.7.0 binary prediction to 5-state model
    if prediction == 1 and p_ensemble >= 0.7:
        classifier_state = "DISTRESS"
        confidence = p_ensemble
    else:
        classifier_state = "CALM"
        confidence = 1.0 - p_ensemble

    return {
        "state": classifier_state,
        "confidence": confidence,
        "p_stress": p_ensemble,
        "p_exercise": 0.0,
        "p_fall": 0.0,
        "calm_probs": [p_short, p_medium, p_long],
        "p_short": p_short,
        "p_medium": p_medium,
        "p_long": p_long,
        "p_ensemble": p_ensemble,
    }


def _compile_c_engine(c_engine_path):
    """Auto-compile the C stdio bridge if binary is missing."""
    c_src = c_engine_path.with_name("kiran_ensemble_stdio.c")
    if not c_src.exists():
        logger.error("C source file not found: %s", c_src)
        return False

    logger.info("Compiling %s...", c_src.name)
    try:
        subprocess.run(
            [
                "gcc", "-O2", "-o", str(c_engine_path),
                str(c_src),
                str(c_engine_path.with_name("kiran_ensemble_v070.c")),
                str(c_engine_path.with_name("kiran_ensemble_v070_data.c")),
                "-lm",
            ],
            check=True,
        )
        logger.info("Compilation successful.")
        return True
    except subprocess.CalledProcessError as e:
        logger.error("Compilation failed: %s", e)
        return False


def _ensure_c_engine(c_engine_path):
    """Ensure the C engine binary exists, compile if needed."""
    if not c_engine_path.exists():
        if not _compile_c_engine(c_engine_path):
            return False
    return True


def _create_c_engine_subprocess(c_engine_path):
    """
    Create a persistent subprocess for the C stdio bridge.
    Returns (Popen, is_new) tuple.
    """
    logger.info("Starting persistent C engine: %s", c_engine_path.name)
    proc = subprocess.Popen(
        [str(c_engine_path)],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        bufsize=0,
    )
    return proc


def _classify_with_retry(c_engine_proc, csv_line):
    """
    Classify using the persistent C engine subprocess.
    If the process dies mid-session, restart it and retry.
    """
    try:
        result = classify_with_ensemble_stdio(csv_line, c_engine_proc)
        return result, c_engine_proc
    except (BrokenPipeError, IOError, OSError) as e:
        logger.warning("C engine pipe broken: %s, restarting...", e)
        try:
            c_engine_proc.kill()
            c_engine_proc.wait(timeout=2)
        except Exception:
            pass
        new_proc = _create_c_engine_subprocess(c_engine_proc.args[0])
        logger.warning("C engine restarted (rolling buffer reset).")
        return classify_with_ensemble_stdio(csv_line, new_proc), new_proc


def main():
    print("=" * 60)
    print("Kiran Live Classifier v0.7.0")
    print("Sensors -> 106 features -> v0.7.0 Ensemble (stdio) -> Gate Chain -> State")
    print("=" * 60)

    if not HAS_GATE_CHAIN:
        print("\nWARNING: kiran_gates module not found. Running without gate chain.")

    if HAS_ATTESTATION:
        print("PQ attestation: ENABLED (ML-DSA-65 via PQCaaS)")
    else:
        print("\nWARNING: kiran.attestation module not found. Running without PQ signing.")

    if not HAS_SENSORS:
        print("\nNo sensor libraries found. Running in DEMO mode with synthetic data.")
        demo_mode = True
    else:
        demo_mode = False

    c_engine = C_ENGINE
    if not _ensure_c_engine(c_engine):
        if C_ENGINE_FALLBACK.exists():
            logger.warning("v0.7.0 engine not found, falling back to old ensemble")
            c_engine = C_ENGINE_FALLBACK
        else:
            logger.error("ERROR: no C engine found.")
            sys.exit(1)

    gate_chain = None
    if HAS_GATE_CHAIN:
        gate_chain = KiranGateChain()

    # Start persistent C engine subprocess
    c_engine_proc = _create_c_engine_subprocess(c_engine)
    window_count = 0
    consecutive_distress = 0

    # Sensor buffers (for demo mode, we'll generate synthetic data)
    eda_buf = []
    hr_buf = []
    temp_buf = []
    bvp_buf = []
    acc_x_buf = []
    acc_y_buf = []
    acc_z_buf = []

    # Sensor initialization (real hardware)
    sensor_obj = None
    if HAS_SENSORS:
        try:
            # I2C setup
            i2c = busio.I2C(board.SCL, board.SDA)

            # BH1750 (ambient light)
            light = adafruit_bh1750.BH1750(i2c)

            # ADS1115 (EDA)
            ads = ADS.ADS1115(i2c)
            eda = AnalogIn(ads, ADS.P0)

            # BH1750 lux reading
            lux = 0.0

            # MPU6050 (accelerometer)
            mpu = adafruit_mpu6050.MPU6050(i2c)

            # Max30102 (HR/SpO2) -- optional
            if HAS_MAX30102:
                try:
                    max30102 = qwiic_max3010x.QwiicMax3010x(i2c)
                    max30102.begin()
                except Exception:
                    max30102 = None
            else:
                max30102 = None

            sensor_obj = {
                "i2c": i2c,
                "light": light,
                "eda": eda,
                "mpu": mpu,
                "max30102": max30102,
            }
            print("Sensors initialized successfully.")
        except Exception as e:
            print(f"Sensor init failed: {e}. Running in DEMO mode.")
            demo_mode = True
            sensor_obj = None

    last_slide_time = time.time()
    state_file = Path("/tmp/kiran_state.json")

    try:
        while True:
            now = time.time()

            # Read sensor data at 4Hz
            if sensor_obj and not demo_mode:
                # EDA
                eda_raw = eda.voltage * 3.3  # scale to 0-3.3V
                eda_buf.append(eda_raw)

                # Temperature (from BH1750 or internal)
                temp_raw = 29.0 + (np.random.rand() - 0.5) * 0.2  # demo fallback
                if sensor_obj.get("mpu"):
                    temp_raw = 29.0
                temp_buf.append(temp_raw)

                # Accelerometer
                if sensor_obj.get("mpu"):
                    ax, ay, az = mpu.acceleration
                    acc_x_buf.append(ax)
                    acc_y_buf.append(ay)
                    acc_z_buf.append(az)

                # HR from Max30102 if available
                if sensor_obj.get("max30102"):
                    try:
                        hr_val = sensor_obj["max30102"].heart_rate
                        if hr_val is not None:
                            hr_buf.append(hr_val)
                        else:
                            hr_buf.append(72.0)
                    except Exception:
                        hr_buf.append(72.0)
                else:
                    hr_buf.append(72.0 + (np.random.rand() - 0.5) * 4)

                # BVP (derived from HR or synthetic)
                bvp_buf.append(72.0 + (np.random.rand() - 0.5) * 2)

                # Lux
                if sensor_obj.get("light"):
                    try:
                        lux = sensor_obj["light"].lux
                    except Exception:
                        lux = 0.0
            else:
                # Demo mode: generate synthetic data
                eda_buf.append(0.5 + (np.random.rand() - 0.5) * 0.1)
                hr_buf.append(72.0 + (np.random.rand() - 0.5) * 4)
                temp_buf.append(29.0 + (np.random.rand() - 0.5) * 0.2)
                bvp_buf.append(72.0 + (np.random.rand() - 0.5) * 2)
                acc_x_buf.append((np.random.rand() - 0.5) * 2)
                acc_y_buf.append((np.random.rand() - 0.5) * 2)
                acc_z_buf.append(9.8 + (np.random.rand() - 0.5) * 0.5)

            # Check if we have a full window
            if len(eda_buf) >= WINDOW_SIZE:
                # Extract features from the window
                eda_window = np.array(eda_buf[-WINDOW_SIZE:])
                hr_window = np.array(hr_buf[-WINDOW_SIZE:])
                temp_window = np.array(temp_buf[-WINDOW_SIZE:])
                bvp_window = np.array(bvp_buf[-WINDOW_SIZE:])
                acc_x_window = np.array(acc_x_buf[-WINDOW_SIZE:])
                acc_y_window = np.array(acc_y_buf[-WINDOW_SIZE:])
                acc_z_window = np.array(acc_z_buf[-WINDOW_SIZE:])

                feats = extract_features(
                    eda_window, hr_window, temp_window,
                    bvp_window, acc_x_window, acc_y_window, acc_z_window,
                )

                # Convert to CSV for C engine
                csv_line = features_to_csv(feats)

                # Classify using persistent C engine
                result, c_engine_proc = _classify_with_retry(c_engine_proc, csv_line)

                window_count += 1

                # Map to richer states via gate chain
                if gate_chain:
                    gate_result = gate_chain.process(
                        features=feats,
                        classifier_state=result["state"],
                        p_stress=result["p_stress"],
                        confidence=result["confidence"],
                    )
                    final_state = gate_result["state"]
                    final_confidence = gate_result["confidence"]
                    alert = gate_result["alert"]
                    sensors_degraded = gate_result["sensors_degraded"]
                    sensor_detail = gate_result.get("sensor_detail", "")
                else:
                    final_state = result["state"]
                    final_confidence = result["confidence"]
                    alert = result["p_stress"] >= 0.7
                    sensors_degraded = False
                    sensor_detail = ""

                # Track consecutive distress for gate chain logic
                if final_state == "DISTRESS":
                    consecutive_distress += 1
                else:
                    consecutive_distress = 0

                # Estimate current sensor values
                current_hr = float(np.mean(hr_window)) if len(hr_window) > 0 else 72.0
                current_eda = float(np.mean(eda_window)) if len(eda_window) > 0 else 0.5
                current_temp = float(np.mean(temp_window)) if len(temp_window) > 0 else 29.0
                current_lux = lux if 'lux' in locals() else 0.0
                current_acc_mag = float(np.sqrt(
                    np.mean(acc_x_window) ** 2 + np.mean(acc_y_window) ** 2 + np.mean(acc_z_window) ** 2
                )) if len(acc_x_window) > 0 else 9.81

                # Build state file output
                ts = datetime.now(timezone.utc).isoformat()
                state = {
                    "state": final_state,
                    "raw_state": result["state"],
                    "confidence": final_confidence,
                    "raw_confidence": result["confidence"],
                    "alert": alert,
                    "sensor_health": "ALL_OK" if not sensors_degraded else "DEGRADED",
                    "sensors_degraded": sensors_degraded,
                    "p_stress": result["p_stress"],
                    "p_exercise": result["p_exercise"],
                    "p_fall": result["p_fall"],
                    "calm_probs": result["calm_probs"],
                    "ts": ts,
                    "window": window_count,
                    "sensors": {
                        "hr": round(current_hr, 1),
                        "eda": round(current_eda, 3),
                        "temp": round(current_temp, 1),
                        "lux": round(current_lux, 1),
                        "accel_mag": round(current_acc_mag, 2),
                    },
                    # v0.7.0 new fields (additive)
                    "p_short": result.get("p_short", 0.0),
                    "p_medium": result.get("p_medium", 0.0),
                    "p_long": result.get("p_long", 0.0),
                    "p_ensemble": result.get("p_ensemble", 0.0),
                    "engine_version": "v0.7.0",
                }

                # Write state file
                try:
                    with open(state_file, "w") as f:
                        json.dump(state, f, indent=2)
                except Exception as e:
                    logger.error("Failed to write state file: %s", e)

                # Display classification
                print(
                    f"Window {window_count}: {final_state} "
                    f"(conf={final_confidence:.3f}, "
                    f"p_stress={result['p_stress']:.3f}, "
                    f"p_ensemble={result.get('p_ensemble', 0.0):.3f})"
                )

                # Attestation (if enabled)
                if HAS_ATTESTATION:
                    try:
                        attest_decision(
                            state=final_state,
                            confidence=final_confidence,
                            window=window_count,
                        )
                    except Exception as e:
                        logger.warning("Attestation failed: %s", e)

                # Slide the window (remove oldest SLIDE_STEP samples)
                del eda_buf[:SLIDE_STEP]
                del hr_buf[:SLIDE_STEP]
                del temp_buf[:SLIDE_STEP]
                del bvp_buf[:SLIDE_STEP]
                del acc_x_buf[:SLIDE_STEP]
                del acc_y_buf[:SLIDE_STEP]
                del acc_z_buf[:SLIDE_STEP]

            # Sleep to maintain 4Hz sampling
            time.sleep(0.25)

    except KeyboardInterrupt:
        print("\nShutting down...")
    finally:
        # Clean up C engine subprocess
        try:
            c_engine_proc.kill()
            c_engine_proc.wait(timeout=2)
        except Exception:
            pass
        print(f"State file written to {state_file}")
        print(f"Total windows processed: {window_count}")


if __name__ == "__main__":
    main()
