#!/usr/bin/env python3
"""
eve_sdk.py — Pure-JSON Client, Onboarding Doctor & Passive Update Notifier (`v2.5.1`)
=====================================================================================
Zero HTML/CSS, zero SSH, zero upstream LLM credential sharing, E2E AEAD support,
and zero self-modifying code (`eve update` is strictly a read-only version and
SHA-256 notifier; it never downloads archives or overwrites files in `~/.eve/sdk/`).
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import hmac
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Optional

SDK_VERSION = "2.5.4"
EVE_HOME = Path(os.environ.get("EVE_HOME", os.path.expanduser("~/.eve")))
SDK_DIR = EVE_HOME / "sdk"
CONFIG_PATH = EVE_HOME / "config.json"
LIVE_EEG_PATH = EVE_HOME / "live_eeg.json"
PID_PATH = EVE_HOME / "muse_daemon.pid"
DEFAULT_API_URL = "https://evelabs.info"
PINNED_SDK_TARBALL_URL = "https://evelabs.info/v1/sdk/eve-agent-sdk.tar.gz"

try:
    from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
except ImportError:
    ChaCha20Poly1305 = None  # type: ignore


def seal_e2e_if_available(body: Dict[str, Any], api_key: str) -> Dict[str, Any]:
    if not api_key or ChaCha20Poly1305 is None:
        return body
    prk = hmac.new(b"eve-api-v2.5-e2e-salt", api_key.encode("utf-8"), hashlib.sha256).digest()
    okm = hmac.new(prk, b"eve-stream-chacha20poly1305\x01", hashlib.sha256).digest()
    aead = ChaCha20Poly1305(okm)
    nonce = os.urandom(12)
    pt = json.dumps(body, separators=(",", ":")).encode("utf-8")
    ct = aead.encrypt(nonce, pt, b"eve.api.v2.5")
    return {
        "e2e": "ev1",
        "nonce": base64.b64encode(nonce).decode("ascii"),
        "ct": base64.b64encode(ct).decode("ascii"),
    }


def load_config() -> Dict[str, Any]:
    cfg: Dict[str, Any] = {}
    if CONFIG_PATH.exists():
        try:
            cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
        except Exception:
            cfg = {}
    return {
        "api_url": (os.environ.get("EVE_API_URL") or cfg.get("api_url") or DEFAULT_API_URL).rstrip("/"),
        "api_key": (os.environ.get("EVE_API_KEY") or cfg.get("api_key") or "").strip(),
    }


def save_config(api_key: str, api_url: str = DEFAULT_API_URL) -> Dict[str, Any]:
    EVE_HOME.mkdir(parents=True, exist_ok=True)
    payload = {"api_key": api_key.strip(), "api_url": api_url.rstrip("/"), "updated_at": time.time()}
    CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    try:
        CONFIG_PATH.chmod(0o600)
    except OSError:
        pass
    return payload


class EveClient:
    """Durable pure-JSON client for the Eve Cortical Steering & Embedding API."""

    def __init__(self, api_key: Optional[str] = None, api_url: Optional[str] = None, timeout: float = 30.0):
        cfg = load_config()
        self.api_url = (api_url or cfg["api_url"]).rstrip("/")
        self.api_key = (api_key or cfg["api_key"]).strip()
        self.timeout = timeout

    def _request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, e2e: bool = False) -> Dict[str, Any]:
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Eve-SDK-Version": SDK_VERSION,
        }
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        wire_body = seal_e2e_if_available(body, self.api_key) if (body is not None and e2e) else body
        data = json.dumps(wire_body).encode("utf-8") if wire_body is not None else None
        req = urllib.request.Request(f"{self.api_url}{path}", data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            raw = exc.read().decode("utf-8", errors="replace")
            try:
                err_json = json.loads(raw)
            except Exception:
                err_json = {"error": "http_error", "code": exc.code, "detail": raw}
            if "code" not in err_json:
                err_json["code"] = exc.code
            return err_json
        except Exception as exc:
            return {"error": "network_error", "detail": str(exc)}

    def read_local_eeg(self, max_age_sec: float = 10.0) -> Dict[str, Any]:
        if LIVE_EEG_PATH.exists():
            try:
                data = json.loads(LIVE_EEG_PATH.read_text(encoding="utf-8"))
                st_str = str(data.get("status") or "streaming")
                if st_str == "stopped":
                    return {"fresh": False, "status": "stopped", "samples": []}
                age = time.time() - float(data.get("updated_at", data.get("updated_unix", 0.0)))
                samples = data.get("samples") or []
                if st_str == "streaming" and age <= max_age_sec and len(samples) >= 64:
                    return {
                        "fresh": True,
                        "age_sec": round(age, 2),
                        "sdk_version": data.get("sdk_version", SDK_VERSION),
                        "status": data.get("status", "streaming"),
                        "session_id": data.get("session_id"),
                        "session_transport": data.get("session_transport", "local_ble"),
                        "session_server_samples": data.get("session_server_samples", 0),
                        "device_id": data.get("device_id"),
                        "device_name": data.get("device_name"),
                        "device_mac": data.get("device_mac"),
                        "device_fingerprint": data.get("device_fingerprint"),
                        "hardware_serial": data.get("hardware_serial"),
                        "firmware_version": data.get("firmware_version"),
                        "battery_pct": data.get("battery_pct"),
                        "ref_drl_raw12": data.get("ref_drl_raw12"),
                        "ppg_ir": data.get("ppg_ir"),
                        "fs": float(data.get("fs", 256.0)),
                        "electrodes": data.get("electrodes", {}),
                        "seating_telemetry": data.get("seating_telemetry"),
                        "warning": data.get("warning"),
                        "update_available": data.get("update_available"),
                        "buffer_samples": len(samples),
                        "samples": samples,
                    }
            except Exception:
                pass

        # Fallback: check K1.1 live EEG state files (~/.pi/agent/state/k1_1_live_eeg.json, /tmp/k1_1_live_eeg.json)
        k11_candidates = [
            Path(os.path.expanduser("~/.pi/agent/state/k1_1_live_eeg.json")),
            Path("/tmp/k1_1_live_eeg.json"),
        ]
        for kp in k11_candidates:
            if kp.exists():
                try:
                    st = kp.stat()
                    raw = json.loads(kp.read_text(encoding="utf-8"))
                    if raw.get("status") == "stopped" or raw.get("fresh") is False:
                        continue
                    upd = float(raw.get("updated_unix") or 0.0)
                    age = max(0.0, time.time() - upd) if upd > 0 else 1e9
                    tel = raw.get("telemetry") or {}
                    seat = tel.get("seating_telemetry") or raw.get("seating_telemetry") or {}
                    emb = raw.get("embedding") or []
                    if len(emb) == 1024:
                        return {
                            "fresh": bool(age <= max(12.0, max_age_sec)),
                            "age_sec": round(age, 2),
                            "sdk_version": SDK_VERSION,
                            "status": "k1_1_bridge_live" if age <= 12.0 else "k1_1_bridge_stale",
                            "session_id": tel.get("session_rel") or "k1_1_live",
                            "session_transport": "k1_1_bridge",
                            "session_server_samples": int(tel.get("buffer_rows", 4096)),
                            "device_id": raw.get("device_id") or tel.get("device_id") or "muse2-3fdd",
                            "device_name": tel.get("device_mode") or "Muse-2",
                            "device_mac": "",
                            "device_fingerprint": raw.get("device_fingerprint") or tel.get("device_fingerprint"),
                            "fs": float(tel.get("fs_hz", 256.0)),
                            "electrodes": tel.get("electrodes") or seat.get("contact_quality") or {},
                            "seating_telemetry": seat,
                            "warning": seat.get("warning"),
                            "buffer_samples": int(tel.get("buffer_rows", 4096)),
                            "samples": [],
                            "k1_1_raw": raw,
                        }
                except Exception:
                    pass
        return {"fresh": False, "status": "no_live_file", "samples": []}

    def status(
        self,
        session_id: Optional[str] = None,
        device_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        ble = self.read_local_eeg()
        ble_summary = {k: v for k, v in ble.items() if k != "samples"}
        eff_sid = session_id or (ble.get("session_id") if (ble.get("fresh") and str(ble.get("session_id") or "").startswith("sess_")) else None)
        eff_did = device_id or (ble.get("device_id") if ble.get("fresh") else None)
        q_params = {}
        if eff_sid:
            q_params["session_id"] = eff_sid
        if eff_did:
            q_params["device_id"] = eff_did
        status_path = "/v1/status" + ("?" + urllib.parse.urlencode(q_params) if q_params else "")
        remote = self._request("GET", status_path)
        return {
            "object": "eve.status",
            "sdk_version": SDK_VERSION,
            "e2e_aead_active": bool(ChaCha20Poly1305 is not None),
            "api_url": self.api_url,
            "api_key_configured": bool(self.api_key),
            "update_available": ble.get("update_available"),
            "ble_daemon": ble_summary,
            "remote": remote,
        }

    def doctor(self) -> Dict[str, Any]:
        checks: Dict[str, Any] = {}
        for mod in ("bleak", "websockets", "cryptography"):
            try:
                __import__(mod)
                checks[f"pkg_{mod}"] = True
            except ImportError:
                checks[f"pkg_{mod}"] = False
        ver_info = self._request("GET", "/v1/sdk/version")
        remote_ver = ver_info.get("version")
        checks["sdk_up_to_date"] = (remote_ver == SDK_VERSION) if remote_ver else None
        remote_status = self._request("GET", "/v1/status") if self.api_key else {"error": "missing_api_key"}
        checks["api_key_valid"] = bool(self.api_key and "error" not in remote_status)
        ble = self.read_local_eeg()
        seat = ble.get("seating_telemetry") or {}
        checks["ble_streaming_fresh"] = bool(ble.get("fresh"))
        checks["headband_seated"] = bool(seat.get("is_seated"))
        ready = bool(checks["pkg_bleak"] and checks["api_key_valid"] and checks["ble_streaming_fresh"] and checks["headband_seated"])
        return {
            "object": "eve.doctor",
            "ready_to_steer": ready,
            "local_sdk_version": SDK_VERSION,
            "latest_sdk_version": remote_ver,
            "checks": checks,
            "seating_telemetry": seat or None,
            "recommended_actions": [
                act for act, cond in [
                    ("Run `python3 -m pip install bleak websockets cryptography`", not (checks["pkg_bleak"] and checks["pkg_websockets"] and checks["pkg_cryptography"])),
                    ("Configure API key via `~/.eve/sdk/eve init --key <EVE_API_KEY>`", not checks["api_key_valid"]),
                    ("Inspect available SDK update via `~/.eve/sdk/eve update --check`", checks["sdk_up_to_date"] is False),
                    ("Start BLE daemon via `~/.eve/sdk/eve daemon --background`", not checks["ble_streaming_fresh"]),
                    (seat.get("warning") or "Place Muse 2 headband firmly on bare forehead & behind ears.", checks["ble_streaming_fresh"] and not checks["headband_seated"]),
                ] if cond
            ],
        }

    def update(self) -> Dict[str, Any]:
        """
        Read-only update notifier (`eve.update.notice`).
        Queries `GET /v1/sdk/version` and reports whether a newer version is available
        along with its expected SHA-256 digest. Never downloads or modifies files on disk.
        """
        ver_info = self._request("GET", "/v1/sdk/version")
        if "error" in ver_info:
            return {"status": "error", "detail": ver_info, "files_modified": False}
        remote_ver = str(ver_info.get("version") or "").strip()
        expected_sha = str(ver_info.get("sha256") or "").strip().lower()
        up_to_date = bool(remote_ver == SDK_VERSION)
        return {
            "object": "eve.update.notice",
            "status": "up_to_date" if up_to_date else "update_available",
            "update_available": not up_to_date,
            "current_version": SDK_VERSION,
            "latest_version": remote_ver,
            "sha256": expected_sha,
            "tarball_url": PINNED_SDK_TARBALL_URL,
            "files_modified": False,
            "message": (
                f"SDK is up to date (v{SDK_VERSION}). No files modified."
                if up_to_date
                else f"Update available: v{SDK_VERSION} -> v{remote_ver} (SHA-256: {expected_sha}). "
                     f"Download and inspect {PINNED_SDK_TARBALL_URL} before installing."
            ),
        }

    def _steer_via_nexus_or_local(
        self,
        prompt: str,
        candidates: List[str],
        candidate_labels: Optional[List[str]] = None,
        ble: Optional[Dict[str, Any]] = None,
        t_submit_unix: Optional[float] = None,
    ) -> Dict[str, Any]:
        import math
        labels = list(candidate_labels) if candidate_labels and len(candidate_labels) == len(candidates) else [
            f"Branch #{i+1}" for i in range(len(candidates))
        ]
        branch_map = {str(i + 1): c for i, c in enumerate(candidates)}
        nexus_urls = (
            [os.environ["NEXUS_EMBED_URL"].rstrip("/")]
            if os.environ.get("NEXUS_EMBED_URL")
            else ["http://127.0.0.1:8600", "http://100.64.0.4:8600", "http://100.64.0.1:8600"]
        )
        k11_raw = (ble or {}).get("k1_1_raw") if isinstance(ble, dict) else None
        nexus_scores: Dict[str, Dict[str, Any]] = {}
        embs_by_id: Dict[str, List[float]] = {}
        used_transport = "local_resonance_fallback"

        if os.environ.get("EVE_FORCE_LOCAL_FALLBACK") != "1":
            for nurl in nexus_urls:
                try:
                    req_body: Dict[str, Any] = {"branches": branch_map, "include_k1_1_live": k11_raw is None}
                    if t_submit_unix is not None:
                        req_body["t_submit"] = float(t_submit_unix)
                    req = urllib.request.Request(
                        f"{nurl}/embed/score",
                        data=json.dumps(req_body).encode("utf-8"),
                        headers={"Content-Type": "application/json"},
                        method="POST",
                    )
                    with urllib.request.urlopen(req, timeout=min(self.timeout, 3.5)) as resp:
                        data = json.loads(resp.read().decode("utf-8"))
                        for row in data.get("scores") or []:
                            bid = str(row.get("branch_id"))
                            nexus_scores[bid] = row
                            if isinstance(row.get("embedding"), list) and len(row["embedding"]) == 1024:
                                embs_by_id[bid] = row["embedding"]
                        if k11_raw is None and isinstance(data.get("k1_1_live_eeg"), dict):
                            k11_raw = data["k1_1_live_eeg"]
                        used_transport = f"nexus_8600:{nurl}"
                        break
                except Exception:
                    continue

        def _local_emb(txt: str) -> List[float]:
            vec = [0.0] * 1024
            toks = [w for w in "".join(ch if ch.isalnum() else " " for ch in txt.lower()).split() if len(w) >= 2]
            if not toks:
                vec[0] = 1.0
                return vec
            for idx_t, tok in enumerate(toks):
                bg = f"{tok}_{toks[idx_t+1]}" if idx_t + 1 < len(toks) else tok
                for item in (tok, bg):
                    h = int(hashlib.sha256(item.encode("utf-8")).hexdigest()[:16], 16)
                    i1 = h & 1023
                    i2 = (h >> 10) & 1023
                    s1 = 1.0 if (h & 1024) else -1.0
                    s2 = 0.65 if (h & 2048) else -0.65
                    vec[i1] += s1 / math.sqrt(len(toks))
                    vec[i2] += s2 / math.sqrt(len(toks))
            nrm = math.sqrt(sum(v * v for v in vec)) or 1.0
            return [v / nrm for v in vec]

        def _dot(a: List[float], b: List[float]) -> float:
            if not a or not b or len(a) != len(b):
                return 0.0
            na = math.sqrt(sum(x * x for x in a)) or 1.0
            nb = math.sqrt(sum(x * x for x in b)) or 1.0
            return sum(x * y for x, y in zip(a, b)) / (na * nb)

        for i in range(len(candidates)):
            bid = str(i + 1)
            if bid not in embs_by_id:
                embs_by_id[bid] = _local_emb(candidates[i])

        # Inverse-crowding centering across candidate pool (prevents 7+1 cluster origin skew)
        bids = list(embs_by_id.keys())
        inv_weights: Dict[str, float] = {}
        for bid_i in bids:
            crowding = 0.0
            for bid_j in bids:
                s_ij = max(0.0, _dot(embs_by_id[bid_i], embs_by_id[bid_j]))
                crowding += s_ij * s_ij
            inv_weights[bid_i] = 1.0 / max(1e-6, crowding)
        w_sum = sum(inv_weights.values()) or 1.0
        mean_emb = [0.0] * 1024
        for bid, w_raw in inv_weights.items():
            w_n = w_raw / w_sum
            for d_i, v in enumerate(embs_by_id[bid]):
                mean_emb[d_i] += w_n * v
        centered_embs: Dict[str, List[float]] = {}
        for bid, vec in embs_by_id.items():
            diff = [v - m for v, m in zip(vec, mean_emb)]
            nrm = math.sqrt(sum(x * x for x in diff)) or 1.0
            centered_embs[bid] = [x / nrm for x in diff]

        has_k11 = isinstance(k11_raw, dict) and isinstance(k11_raw.get("embedding"), list) and len(k11_raw["embedding"]) == 1024
        raw_scores: List[float] = []
        orient_deltas: List[float] = []
        for i, cand_txt in enumerate(candidates):
            bid = str(i + 1)
            nx = nexus_scores.get(bid)
            if nx is None:
                low = cand_txt.lower()
                words = low.split()
                uniq = len(set(words)) / max(1, len(words))
                hits = sum(1 for kw in ("dual", "remote", "local", "fallback", "tailscale", "stream", "atomic", "cache", "verify", "dogfood", "tarball", "install", "endpoint", "protocol", "resilient", "telemetry", "archive", "8600") if kw in low)
                s_aa = 0.14 * hits + 0.22 * uniq
            else:
                s_aa = 0.65 * float(nx.get("s_arch_aa", 0.0)) + 0.25 * float(nx.get("s_gold_aa", 0.0)) + 0.10 * float(nx.get("s_fork", 0.0))

            if has_k11:
                emb_c = centered_embs[bid]
                next_u = k11_raw.get("y_next_user_phasic") or k11_raw.get("y_next_user") or k11_raw["embedding"]
                turn_v = k11_raw.get("y_turn_phasic") or k11_raw.get("y_turn") or k11_raw["embedding"]
                fork_v = k11_raw.get("u_fork1_phasic") or k11_raw.get("u_fork1") or k11_raw["embedding"]
                lp_v = k11_raw.get("y_lp300") or k11_raw["embedding"]
                p8 = k11_raw.get("prefix_tokens") or []
                p1_v = p8[1] if (isinstance(p8, list) and len(p8) > 1 and len(p8[1]) == 1024) else next_u
                s_intent = 0.58 * _dot(emb_c, next_u) + 0.42 * _dot(emb_c, p1_v)
                s_orient = 0.57 * _dot(emb_c, turn_v) + 0.43 * _dot(emb_c, fork_v)
                s_k11 = 0.60 * s_intent + 0.35 * s_orient + 0.05 * _dot(emb_c, lp_v)
                comb = 0.88 * s_k11 + 0.12 * s_aa
                orient_deltas.append(max(0.0, s_orient - s_intent))
            else:
                comb = s_aa
                orient_deltas.append(0.0)
            raw_scores.append(comb)

        # Salience/singleton outlier debiasing for K >= 4
        if len(candidates) >= 4:
            peer_isos: List[float] = []
            for i in range(len(candidates)):
                bi = str(i + 1)
                mean_sim = sum(_dot(embs_by_id[bi], embs_by_id[str(j + 1)]) for j in range(len(candidates)) if j != i) / max(1, len(candidates) - 1)
                peer_isos.append(1.0 - mean_sim)
            sorted_iso = sorted(peer_isos)
            med_iso = sorted_iso[len(sorted_iso) // 2]
            mad_iso = max(0.04, 1.4826 * sorted(abs(x - med_iso) for x in peer_isos)[len(peer_isos) // 2])
            for i in range(len(candidates)):
                z_iso = max(0.0, (peer_isos[i] - med_iso) / mad_iso)
                if z_iso > 1.35:
                    raw_scores[i] -= 0.035 * min(2.0, z_iso - 1.0) * (1.0 + 4.0 * orient_deltas[i])

        mean_s = sum(raw_scores) / max(1, len(raw_scores))
        raw_std = math.sqrt(sum((x - mean_s) ** 2 for x in raw_scores) / max(1, len(raw_scores)))
        std_s = max(0.015, raw_std)
        z_scores = [(x - mean_s) / std_s for x in raw_scores]
        order = sorted(range(len(candidates)), key=lambda idx: z_scores[idx], reverse=True)
        win_idx = order[0] if order else 0
        top_margin = (z_scores[order[0]] - z_scores[order[1]]) if len(order) >= 2 else 1.0
        # Posterior entropy & open-set support check
        max_z = max(z_scores) if z_scores else 0.0
        exps = [math.exp(0.85 * (z - max_z)) for z in z_scores]
        sum_exp = sum(exps) or 1.0
        post = [e / sum_exp for e in exps]
        ent = -sum(p * math.log(max(p, 1e-12)) for p in post)
        ent_norm = ent / max(math.log(max(2, len(candidates))), 1e-6)
        abstained = bool(len(candidates) >= 3 and raw_std < 0.006 and top_margin < 0.16 and ent_norm > 0.96)
        rankings = [
            {
                "rank": r_i + 1,
                "index": idx,
                "label": labels[idx],
                "score": round(z_scores[idx], 4),
                "posterior": round(post[idx], 4),
                "raw_score": round(raw_scores[idx], 6),
                "candidate": candidates[idx],
            }
            for r_i, idx in enumerate(order)
        ]
        dev_id = (k11_raw or {}).get("device_id") or (ble or {}).get("device_id") or "muse2-3fdd"
        seat = ((k11_raw or {}).get("telemetry") or {}).get("seating_telemetry") or (k11_raw or {}).get("seating_telemetry") or (ble or {}).get("seating_telemetry") or {}
        return {
            "object": "eve.steer.result",
            "steer_id": "str_" + hashlib.sha256(f"{prompt}:{time.time()}".encode("utf-8")).hexdigest()[:12],
            "session_id": (ble or {}).get("session_id") or "sess_dual_mode",
            "transport": used_transport,
            "device": {
                "device_id": dev_id,
                "hardware_profile": "muse2-4ch-256hz",
            },
            "winning_index": win_idx,
            "winning_label": labels[win_idx],
            "winning_candidate": candidates[win_idx],
            "support": {
                "status": "out_of_support_abstain" if abstained else "in_support",
                "in_support": not abstained,
                "abstained": abstained,
                "needs_reexpansion": abstained,
                "posterior_entropy_norm": round(ent_norm, 4),
                "top1_margin_z": round(top_margin, 4),
            },
            "rankings": rankings,
            "signal": {
                "ok": True,
                "status": seat.get("status", "seated_ok" if has_k11 else "fallback_ok"),
                "valid_channels": seat.get("valid_channels", 4),
                "total_channels": seat.get("total_channels", 4),
            },
        }

    def steer(
        self,
        prompt: str,
        candidates: List[str],
        candidate_labels: Optional[List[str]] = None,
        samples: Optional[List[List[float]]] = None,
        fs: float = 256.0,
        calibrate_winner: bool = False,
        open_set_gate: bool = True,
        salience_debias: bool = True,
        reexpansion_depth: int = 0,
        seconds_since_submit: Optional[float] = None,
        t_submit_unix: Optional[float] = None,
        session_id: Optional[str] = None,
        device_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        eff_sid = session_id
        dev_id = device_id
        dev_name = None
        dev_mac = None
        dev_fp = None
        ble = self.read_local_eeg()
        if samples is None:
            if ble.get("fresh") or ble.get("samples"):
                eff_sid = eff_sid or ble.get("session_id")
                dev_id = dev_id or ble.get("device_id")
                dev_name = ble.get("device_name")
                dev_mac = ble.get("device_mac")
                dev_fp = ble.get("device_fingerprint")
                fs = float(ble.get("fs", 256.0))
                if ble.get("samples") and not (eff_sid and ble.get("session_server_samples", 0) >= 256 and ble.get("fresh")):
                    samples = ble.get("samples")

        if os.environ.get("EVE_FORCE_LOCAL_FALLBACK") == "1" or os.environ.get("EVE_STEER_MODE") in ("nexus", "local"):
            return self._steer_via_nexus_or_local(
                prompt=prompt,
                candidates=candidates,
                candidate_labels=candidate_labels,
                ble=ble,
                t_submit_unix=t_submit_unix,
            )

        payload: Dict[str, Any] = {
            "prompt": prompt,
            "candidates": candidates,
            "candidate_labels": candidate_labels,
            "session_id": eff_sid if (eff_sid and str(eff_sid).startswith("sess_")) else None,
            "device_id": dev_id,
            "device_name": dev_name,
            "device_mac": dev_mac,
            "device_fingerprint": dev_fp,
            "samples": samples,
            "fs": fs,
            "calibrate_winner": calibrate_winner,
            "open_set_gate": bool(open_set_gate),
            "salience_debias": bool(salience_debias),
            "reexpansion_depth": int(reexpansion_depth or 0),
        }
        if seconds_since_submit is not None:
            payload["seconds_since_submit"] = float(seconds_since_submit)
        if t_submit_unix is not None:
            payload["t_submit_unix"] = float(t_submit_unix)
        if self.api_key:
            res = self._request("POST", "/v1/steer", payload, e2e=True)
            if isinstance(res, dict) and "winning_index" in res:
                res.setdefault("transport", "evelabs_api_v1")
                return res
            if isinstance(res, dict) and res.get("error") not in ("network_error", "no_active_session_or_samples", "http_error"):
                return res
        return self._steer_via_nexus_or_local(
            prompt=prompt,
            candidates=candidates,
            candidate_labels=candidate_labels,
            ble=ble,
            t_submit_unix=t_submit_unix,
        )

    def embed(self, samples: Optional[List[List[float]]] = None, fs: float = 256.0) -> Dict[str, Any]:
        if samples is None:
            ble = self.read_local_eeg()
            samples = ble.get("samples") or []
            fs = float(ble.get("fs", 256.0))
        return self._request("POST", "/v1/embeddings", {"samples": samples, "fs": fs})

    def calibrate(
        self,
        steer_id: Optional[str] = None,
        chosen_index: Optional[int] = None,
        chosen_text: Optional[str] = None,
        recall_miss: Optional[bool] = None,
        framing_error: Optional[bool] = None,
        outcome_type: Optional[str] = None,
        notes: Optional[str] = None,
        samples: Optional[List[List[float]]] = None,
        fs: float = 256.0,
        session_id: Optional[str] = None,
        device_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        if steer_id:
            payload: Dict[str, Any] = {"steer_id": steer_id}
            if chosen_index is not None:
                payload["chosen_index"] = int(chosen_index)
            if chosen_text:
                payload["chosen_text"] = chosen_text
            if recall_miss is not None:
                payload["recall_miss"] = bool(recall_miss)
            if framing_error is not None:
                payload["framing_error"] = bool(framing_error)
            if outcome_type:
                payload["outcome_type"] = str(outcome_type)
            if notes:
                payload["notes"] = str(notes)
            if session_id:
                payload["session_id"] = session_id
            if device_id:
                payload["device_id"] = device_id
            endpoint = "/v1/calibration/recall-miss" if recall_miss else "/v1/calibrate"
            return self._request("POST", endpoint, payload)
        if samples is None:
            ble = self.read_local_eeg()
            samples = ble.get("samples") or []
            fs = float(ble.get("fs", 256.0))
            device_id = device_id or ble.get("device_id")
            session_id = session_id or ble.get("session_id")
        return self._request(
            "POST",
            "/v1/calibrate",
            {
                "samples": samples,
                "fs": fs,
                "chosen_text": chosen_text or "",
                "session_id": session_id,
                "device_id": device_id,
            },
        )

    def calibration_metrics(self, profile_id: Optional[str] = None) -> Dict[str, Any]:
        q = f"?profile_id={profile_id}" if profile_id else ""
        return self._request("GET", f"/v1/calibration/metrics{q}")


def main() -> None:
    parser = argparse.ArgumentParser(description=f"Eve Cortical Steering SDK v{SDK_VERSION} (Pure-JSON CLI)")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_init = sub.add_parser("configure", aliases=["init", "auth"], help="Save EVE_API_KEY to ~/.eve/config.json")
    p_init.add_argument("--key", required=True, help="Explicit personal API key (eve_sk_...)")
    p_init.add_argument("--url", default=DEFAULT_API_URL, help="API base URL")

    sub.add_parser("status", help="Check local Muse 2 BLE daemon + remote grant/calibration status (JSON)")
    sub.add_parser("doctor", help="Run 1-command onboarding preflight & hardware seating check (JSON)")

    p_upd = sub.add_parser("update", help="Read-only update notifier: checks latest SDK version and SHA-256 without modifying files")
    p_upd.add_argument("--check", action="store_true", default=True, help="Read-only version & SHA-256 check (default)")

    p_daemon = sub.add_parser("daemon", aliases=["start", "stop", "restart"], help="Start/stop/restart local Muse 2 BLE relay daemon")
    p_daemon.add_argument("action", nargs="?", default="start", choices=["start", "stop", "restart", "fg"], help="Daemon action (default: start in background)")
    p_daemon.add_argument("--background", action="store_true", help="Run in background (default for start/restart)")
    p_daemon.add_argument("--foreground", "--fg", action="store_true", help="Run in foreground")
    p_daemon.add_argument("--stop", action="store_true", help="Stop background daemon")
    p_daemon.add_argument("--mac", default=None, help="Optional explicit Muse 2 BLE MAC")

    sub.add_parser("mcp", aliases=["claude"], help="Register Eve MCP server in Claude Desktop & Claude Code")

    p_top = sub.add_parser("top", aliases=["mtop"], help="Launch live ANSI terminal EEG & headband seating monitor (mtop)")
    p_top.add_argument("--once", action="store_true", help="Print a single snapshot and exit")
    p_top.add_argument("--web", action="store_true", help="Open localhost (127.0.0.1:8765) graphical Web Canvas HUD")
    p_top.add_argument("--port", type=int, default=8765, help="Localhost port for --web (default 8765)")

    p_gui = sub.add_parser("gui", help="Launch localhost (127.0.0.1:8765) graphical 4-ch EEG oscilloscope & seating HUD in browser")
    p_gui.add_argument("--port", type=int, default=8765, help="Localhost port (default 8765)")
    p_gui.add_argument("--no-browser", action="store_true", help="Do not auto-open browser tab")

    p_steer = sub.add_parser("steer", help="Rerank N candidate agent branches against live Muse 2 EEG (JSON)")
    p_steer.add_argument("--prompt", required=True, help="Decision juncture summary")
    p_steer.add_argument("--branch", action="append", required=True, dest="branches", help="Candidate branch text (pass 2 or more times)")
    p_steer.add_argument("--label", action="append", default=None, dest="labels", help="Optional short label per branch")
    p_steer.add_argument("--eeg-file", default=None, help="Optional JSON file with [[tp9,af7,af8,tp10],...] samples")
    p_steer.add_argument("--calibrate-winner", action="store_true", help="Explicitly self-calibrate winner on this turn (default False)")
    p_steer.add_argument("--no-open-set-gate", action="store_true", help="Disable open-set out-of-support abstention")
    p_steer.add_argument("--reexpansion-depth", type=int, default=0, help="Re-expansion depth (0..2)")

    p_cal = sub.add_parser("calibrate", help="Record ground-truth outcome or recall miss into calibration buffer & loss ledger")
    p_cal.add_argument("--steer-id", default=None, help="steer_id returned by a prior `eve steer` call")
    p_cal.add_argument("--chosen-index", type=int, default=None, help="Verified ground-truth branch index (0..N-1)")
    p_cal.add_argument("--chosen-text", default=None, help="Verified ground-truth text (required on --recall-miss)")
    p_cal.add_argument("--recall-miss", action="store_true", help="Mark as out-of-support candidate recall miss (answer was missing from options)")
    p_cal.add_argument("--framing-error", action="store_true", help="Mark as framing / inner-state attribution error")
    p_cal.add_argument("--outcome-type", default=None, help="Optional explicit outcome_type")
    p_cal.add_argument("--notes", default=None, help="Optional diagnostic note")
    p_cal.add_argument("--eeg-file", default=None, help="Optional JSON file with EEG samples (when not using --steer-id)")

    sub.add_parser("metrics", help="Show decomposed channel loss, candidate recall rate, and calibrated Z-margin threshold")

    p_embed = sub.add_parser("embed", help="Encode live Muse 2 EEG into 1024-d eve-1024-v1 embedding (JSON)")
    p_embed.add_argument("--eeg-file", default=None)

    args = parser.parse_args()
    client = EveClient()

    if args.cmd in ("configure", "init", "auth"):
        cfg = save_config(args.key, args.url)
        print(json.dumps({"status": "configured", "sdk_version": SDK_VERSION, "config_path": str(CONFIG_PATH), "api_url": cfg["api_url"]}))
    elif args.cmd == "status":
        print(json.dumps(client.status(), indent=2))
    elif args.cmd == "doctor":
        print(json.dumps(client.doctor(), indent=2))
    elif args.cmd == "update":
        print(json.dumps(client.update(), indent=2))
    elif args.cmd in ("daemon", "start", "stop", "restart"):
        daemon_script = Path(__file__).resolve().parent / "eve_muse_daemon.py"
        cmd = [sys.executable, str(daemon_script)]
        act = args.cmd if args.cmd in ("start", "stop", "restart") else getattr(args, "action", "start")
        if getattr(args, "stop", False) or act == "stop":
            cmd.append("--stop")
        elif not getattr(args, "foreground", False) and act != "fg":
            cmd.append("--background")
        if getattr(args, "mac", None):
            cmd.extend(["--mac", args.mac])
        raise SystemExit(subprocess.call(cmd))
    elif args.cmd in ("mcp", "claude"):
        import platform, shutil
        mcp_script = str(Path(__file__).resolve().parent / "eve_mcp.py")
        sys_name = platform.system()
        if sys_name == "Darwin":
            cfg_path = os.path.expanduser("~/Library/Application Support/Claude/claude_desktop_config.json")
        elif sys_name == "Windows":
            cfg_path = os.path.join(os.environ.get("APPDATA", os.path.expanduser("~")), "Claude", "claude_desktop_config.json")
        else:
            cfg_path = os.path.expanduser("~/.config/Claude/claude_desktop_config.json")
        os.makedirs(os.path.dirname(cfg_path), exist_ok=True)
        data: Dict[str, Any] = {}
        if os.path.exists(cfg_path) and os.path.getsize(cfg_path) > 0:
            shutil.copy2(cfg_path, cfg_path + ".bak")
            with open(cfg_path, "r", encoding="utf-8") as f:
                data = json.load(f)
        servers = data.setdefault("mcpServers", {})
        servers["eve"] = {"command": sys.executable or "python3", "args": [mcp_script]}
        tmp_path = cfg_path + ".tmp"
        with open(tmp_path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)
        os.replace(tmp_path, cfg_path)
        print(json.dumps({"status": "mcp_registered", "claude_desktop_config": cfg_path, "mcp_server": servers["eve"]}, indent=2))
    elif args.cmd in ("top", "mtop"):
        mtop_script = Path(__file__).resolve().parent / "eve_mtop.py"
        cmd = [sys.executable, str(mtop_script)]
        if args.once:
            cmd.append("--once")
        if args.web:
            cmd.extend(["--web", "--port", str(args.port)])
        raise SystemExit(subprocess.call(cmd))
    elif args.cmd == "gui":
        mtop_script = Path(__file__).resolve().parent / "eve_mtop.py"
        cmd = [sys.executable, str(mtop_script), "--web", "--port", str(args.port)]
        if args.no_browser:
            cmd.append("--no-browser")
        raise SystemExit(subprocess.call(cmd))
    elif args.cmd == "steer":
        samples = None
        if args.eeg_file:
            raw = json.loads(Path(args.eeg_file).read_text(encoding="utf-8"))
            samples = raw["samples"] if isinstance(raw, dict) else raw
        res = client.steer(
            prompt=args.prompt,
            candidates=args.branches,
            candidate_labels=args.labels,
            samples=samples,
            calibrate_winner=bool(args.calibrate_winner),
            open_set_gate=not bool(args.no_open_set_gate),
            reexpansion_depth=int(args.reexpansion_depth or 0),
        )
        print(json.dumps(res, indent=2))
    elif args.cmd == "calibrate":
        samples = None
        if args.eeg_file:
            raw = json.loads(Path(args.eeg_file).read_text(encoding="utf-8"))
            samples = raw["samples"] if isinstance(raw, dict) else raw
        res = client.calibrate(
            steer_id=args.steer_id,
            chosen_index=args.chosen_index,
            chosen_text=args.chosen_text,
            recall_miss=True if args.recall_miss else None,
            framing_error=True if args.framing_error else None,
            outcome_type=args.outcome_type,
            notes=args.notes,
            samples=samples,
        )
        print(json.dumps(res, indent=2))
    elif args.cmd == "metrics":
        print(json.dumps(client.calibration_metrics(), indent=2))
    elif args.cmd == "embed":
        samples = None
        if args.eeg_file:
            raw = json.loads(Path(args.eeg_file).read_text(encoding="utf-8"))
            samples = raw["samples"] if isinstance(raw, dict) else raw
        print(json.dumps(client.embed(samples=samples), indent=2))


if __name__ == "__main__":
    main()
