"""THE 3D AVATAR — the front door.

What it is
----------
One browser page (``GET /avatar``) that renders an abstract, geometric head with
Three.js and reacts to the events the system already produces:

    IDLE       slow breathing, head drift, eyes following the pointer
    LISTENING  speech recognition is active: eyes brighten, a ring pulses
    THINKING   a command was POSTed to /api/voice/command and the reply is pending:
               a rotating ring and a particle shimmer
    SPEAKING   speechSynthesis is talking: the mouth bar moves with the utterance
               and the emissive intensity pulses on every boundary event

What it is NOT
--------------
A model of the system's cognition. The face is a *visual front door*: the states
are real (they are driven by the browser's speech events and by the command
round-trip), but the head does not represent, visualise or reveal any internal
reasoning. There is no internal monologue to show — the orchestrator is a
deterministic pipeline and a hash-chained ledger. The page says this on screen.

The avatar is a registered tool component: it owns no pipeline state, its page
renders in the browser, and only the state *transitions the user actually causes*
are written to the audit ledger (``avatar.state``), so the demo is traceable.
"""

from __future__ import annotations

import logging

from . import audit
from .errors import ValidationError

log = logging.getLogger("jarvis.avatar")

COMPONENT_NAME = "AvatarFace"

STATE_IDLE = "IDLE"
STATE_LISTENING = "LISTENING"
STATE_THINKING = "THINKING"
STATE_SPEAKING = "SPEAKING"
STATES = (STATE_IDLE, STATE_LISTENING, STATE_THINKING, STATE_SPEAKING)

#: Three.js is loaded from a CDN through an import map. Pinned: an unpinned
#: URL would silently change the renderer under the page.
THREE_VERSION = "0.160.0"
THREE_CDN = f"https://unpkg.com/three@{THREE_VERSION}/build/three.module.js"
THREE_FALLBACK_CDN = f"https://cdn.jsdelivr.net/npm/three@{THREE_VERSION}/build/three.module.js"

STATE_MEANING = {
    STATE_IDLE: "nothing is being said, heard or asked",
    STATE_LISTENING: "the browser's speech recognition is on",
    STATE_THINKING: "a command was POSTed to /api/voice/command and the reply is pending",
    STATE_SPEAKING: "speechSynthesis is reading a reply out loud",
}

HONESTY = (
    "The avatar is a visual front door, not a model of the system's cognition. The four states "
    "are driven by real events — the browser's speech recognition, the speechSynthesis utterance, "
    "and the round-trip to /api/voice/command — but the face does not represent or reveal any "
    "internal reasoning, and there is no internal monologue to reveal: the orchestrator is a "
    "deterministic pipeline plus a hash-chained ledger. Watching the mouth move tells you that "
    "something was spoken, not what the system is 'thinking'. It is not sentient and this page "
    "does not claim otherwise."
)


def normalize_state(state: str | None) -> str:
    value = (state or "").strip().upper()
    if value not in STATES:
        raise ValidationError(
            f"unknown avatar state {state!r}; expected one of {', '.join(STATES)}"
        )
    return value


def record_state(state: str, *, source: str = "avatar-ui", detail: str = "") -> dict:
    """Write one avatar state engagement to the audit ledger.

    Only states the user (or the browser) actually caused are recorded — the page
    never invents a transition to make the demo look busier.
    """
    value = normalize_state(state)
    row = audit.record(
        COMPONENT_NAME, "avatar.state", "avatar", value,
        {
            "state": value,
            "meaning": STATE_MEANING[value],
            "source": source,
            "detail": detail,
            "rendered_in": "browser",
            "visualises_cognition": False,
            "sentient": False,
        },
    )
    log.info("[%s] state %s (source=%s) audit seq %s", COMPONENT_NAME, value, source, row["seq"])
    return {
        "component": COMPONENT_NAME,
        "state": value,
        "meaning": STATE_MEANING[value],
        "source": source,
        "audit_seq": row["seq"],
        "visualises_cognition": False,
    }


def recent_states(limit: int = 8) -> list[dict]:
    return audit.recent(limit=limit, actor=COMPONENT_NAME, action="avatar.state")


def describe() -> dict:
    return {
        "component": COMPONENT_NAME,
        "page": "/avatar",
        "renderer": f"three.js {THREE_VERSION} (ES module, import map)",
        "three_cdn": THREE_CDN,
        "states": list(STATES),
        "state_meaning": dict(STATE_MEANING),
        "webgl_required": True,
        "fallback": "styled panel when WebGL is unavailable",
        "visualises_cognition": False,
        "sentient": False,
        "honesty": HONESTY,
    }


class AvatarFace:
    """Tool component: the front-door avatar. Owns no pipeline state."""

    def __call__(self, job: dict | None = None) -> dict:
        return self.handle(job or {})

    def handle(self, job: dict) -> dict:
        return {
            "to_state": None,  # a tool never transitions a job
            "note": (
                "AVATAR: the front door is a browser-rendered three.js head driven by real "
                "speech/command events. It visualises no cognition and is not sentient."
            ),
            "payload_patch": {},
            "data": {
                "page": "/avatar",
                "states": list(STATES),
                "renderer": f"three.js {THREE_VERSION}",
                "visualises_cognition": False,
            },
        }


def register_avatar(registry) -> object:
    """Register the avatar as a tool component. Idempotent."""
    from .registry import Component

    if registry.has(COMPONENT_NAME):
        return registry.get(COMPONENT_NAME)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=None,
            handler=AvatarFace(),
            description=(
                "The 3D front door: a three.js geometric head whose IDLE / LISTENING / THINKING / "
                "SPEAKING states are driven by real speech and command events. A visual front "
                "door only — it does not represent or reveal any internal reasoning."
            ),
            kind="tool",
        )
    )
