"""Claw3D / OpenClaw consumer — sample side that reads the EMF loop.

Demonstrates how a Claw3D client (e.g. the front-end Three.js agent
visualizer) would consume the four wemeanyounoharm EMF files plus the
``claw3d_agent_state.json`` emitted by ``claw3d_emitter.py``.

Renders a deterministic textual "office state" — useful for unit
testing without a running Claw3D gateway.
"""

from __future__ import annotations

import json
from pathlib import Path

V3_BASE = Path("/home/workspace/ghojualamanchu-v3")
SIGNAL_LOOP_DIR = V3_BASE / "data" / "signals"


def _read(path: Path) -> dict:
    return json.loads(path.read_text())


def render_office_state() -> dict:
    rr = _read(SIGNAL_LOOP_DIR / "resonance_report.json")
    ot = _read(SIGNAL_LOOP_DIR / "oscillation_target.json")
    tlm = _read(SIGNAL_LOOP_DIR / "telemetry.json")
    fb = _read(SIGNAL_LOOP_DIR / "feedback_report.json")
    agent_state_path = SIGNAL_LOOP_DIR / "claw3d_agent_state.json"
    agent_state = _read(agent_state_path) if agent_state_path.exists() else None

    return {
        "beat": rr.get("beat"),
        "field_state": rr.get("field_state"),
        "phase": ot.get("target_phase"),
        "trit": ot.get("trit"),
        "prescription": ot.get("target_prescription"),
        "magnitude": ot.get("magnitude"),
        "alignment": fb.get("alignment_score"),
        "trit_match": fb.get("trit_match"),
        "agent_id": (agent_state or {}).get("agent_id"),
        "room_id": (agent_state or {}).get("room_id"),
        "sources": rr.get("perturbation_sources", []),
    }


def describe(state: dict) -> str:
    """Human-readable description — one paragraph, no jargon."""
    phase_verb = {
        "INHALE": "drawing in",
        "EXHALE": "exhaling",
        "HOLD":   "resting",
    }.get(state.get("phase", "HOLD"), "resting")
    align = state.get("alignment", 0.0)
    if align >= 0.9:
        band = "in resonance"
    elif align >= 0.5:
        band = "partially aligned"
    else:
        band = "off-balance"
    sources = state.get("sources") or []
    src_clause = f" (notable sources: {', '.join(sources)})" if sources else ""
    return (
        f"Beat {state.get('beat')} — agent {state.get('agent_id', '?')} "
        f"in room {state.get('room_id', '?')} is {phase_verb} at "
        f"{state.get('magnitude', 0.0):.2f} magnitude, "
        f"prescription={state.get('prescription')}, "
        f"field={state.get('field_state')}, {band}{src_clause}."
    )


if __name__ == "__main__":
    state = render_office_state()
    print(json.dumps(state, indent=2))
    print()
    print(describe(state))
