"""Claw3D / OpenClaw emitter — push v3 EMF state to a Claw3D gateway.

Reference: https://github.com/iamlukethedev/Claw3D

By default this module does **not** make any network call. Set the
environment variable ``CLAW3D_GATEWAY_URL`` to enable live HTTP POST
emission. The agent_id and room_id are also env-driven so multiple
ghojualamanchu instances can share a Claw3D office without colliding.

Schema follows the OpenClaw agent_state message:
    {
        "type": "agent_state",
        "agent_id": "<string>",
        "room_id":  "<string>",
        "ts":       "<iso-8601 UTC>",
        "beat":     <int>,
        "field_state": "DEAD|CALM|STIR|STORM",
        "trit":     <0|1|2>,
        "phase":    "INHALE|EXHALE|HOLD",
        "magnitude":<float 0..1>,
        "prescription": "<action>",
        "alignment": <float 0..1>,
        "sources":  [<string>, ...]
    }
"""

from __future__ import annotations

import json
import os
import sys
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path

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

GATEWAY_URL = os.environ.get("CLAW3D_GATEWAY_URL", "").rstrip("/")
AGENT_ID    = os.environ.get("CLAW3D_AGENT_ID", "ghojua-v3")
ROOM_ID     = os.environ.get("CLAW3D_ROOM_ID", "earth-breath-room")


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


def build_agent_state() -> dict:
    rr = _read(SIGNAL_LOOP_DIR / "resonance_report.json")
    ot = _read(SIGNAL_LOOP_DIR / "oscillation_target.json")
    fb = _read(SIGNAL_LOOP_DIR / "feedback_report.json")
    return {
        "type": "agent_state",
        "agent_id": AGENT_ID,
        "room_id": ROOM_ID,
        "ts": datetime.now(timezone.utc).isoformat(),
        "beat": rr.get("beat", 0),
        "field_state": rr.get("field_state", "CALM"),
        "trit": ot.get("trit", 2),
        "phase": ot.get("target_phase", "HOLD"),
        "magnitude": round(ot.get("magnitude", 0.0), 3),
        "prescription": ot.get("target_prescription", "calm"),
        "alignment": round(fb.get("alignment_score", 0.0), 3),
        "sources": rr.get("perturbation_sources", []),
    }


def write_agent_state(state: dict) -> Path:
    """Write the agent_state atomically to SIGNAL_LOOP_DIR."""
    SIGNAL_LOOP_DIR.mkdir(parents=True, exist_ok=True)
    out = SIGNAL_LOOP_DIR / "claw3d_agent_state.json"
    tmp = out.with_suffix(".json.tmp")
    tmp.write_text(json.dumps(state, indent=2))
    tmp.replace(out)
    return out


def emit() -> dict:
    """Build, write, and optionally POST the agent_state. Always writes locally."""
    state = build_agent_state()
    write_agent_state(state)
    if GATEWAY_URL:
        url = f"{GATEWAY_URL}/api/agents/{AGENT_ID}/state"
        req = urllib.request.Request(
            url,
            data=json.dumps(state).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=5) as resp:
                state["_http_status"] = resp.status
        except urllib.error.URLError as e:
            state["_http_error"] = str(e)
    return state


if __name__ == "__main__":
    state = emit()
    out = SIGNAL_LOOP_DIR / "claw3d_agent_state.json"
    print(f"wrote {out}")
    print(json.dumps(state, indent=2))
