"""LOCAL VOICE — the first voice channel.

Where the audio lives
---------------------
In the USER'S BROWSER, not here. Speech recognition is the Web Speech API
(``webkitSpeechRecognition`` / ``SpeechRecognition``) and speech synthesis is
``speechSynthesis``. Both run on the user's own machine with the browser's own
engine: no API key, no cloud call from this app, and no audio is uploaded to
this server. This module never receives, stores or transmits audio — it receives
the TRANSCRIPT the browser already produced and nothing else.

What this module does
---------------------
Turns a transcript into a deterministic intent (no model, no guessing), runs the
matching existing layer, builds the sentence that will be spoken back, and writes
one audit row per command through ``orchestrator.audit.record()`` so there is a
record of what was said and what it did.

Supported intents
-----------------
    status         loop counts (jobs per state) + signals/opportunities/bots
    opportunities  the top scored opportunities
    bots           bot specs and their keep-or-kill verdicts
    audit          audit chain length and integrity
    tick           run exactly one scheduling tick
    help           the command list

Anything else resolves to ``not_understood`` with a plain "here is what I can
do" reply. It never guesses an intent for input it did not match.
"""

from __future__ import annotations

import logging
import re

from . import audit
from . import state_machine as sm

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

COMPONENT_NAME = "VoiceConsole"

INTENT_STATUS = "status"
INTENT_OPPORTUNITIES = "opportunities"
INTENT_BOTS = "bots"
INTENT_AUDIT = "audit"
INTENT_TICK = "tick"
INTENT_HELP = "help"
INTENT_UNKNOWN = "not_understood"
INTENTS = (
    INTENT_STATUS,
    INTENT_OPPORTUNITIES,
    INTENT_BOTS,
    INTENT_AUDIT,
    INTENT_TICK,
    INTENT_HELP,
    INTENT_UNKNOWN,
)

HONESTY = (
    "Recognition and synthesis run in your browser (Web Speech API). No API key, no audio "
    "leaves this device. Chrome and Edge implement recognition; Safari's support is partial "
    "and Firefox ships none by default, so the page says so and offers a typed fallback. "
    "Intents are matched by keyword, deterministically — there is no language model here, and "
    "unmatched speech is refused rather than guessed."
)

#: Ordered: the first intent whose keyword or phrase appears wins. Order matters
#: because a sentence like "run a tick and show the status" is ambiguous; the
#: more specific verb is preferred.
COMMANDS = (
    {
        "intent": INTENT_HELP,
        "keywords": ("help", "commands", "command", "instructions", "options"),
        "phrases": ("what can you do", "what can i say", "what can i ask", "what do you do",
                    "list commands"),
        "say": "help",
        "description": "List the commands this console understands.",
    },
    {
        "intent": INTENT_TICK,
        "keywords": ("tick",),
        "phrases": ("run a tick", "run the scheduler", "run the schedule", "fire the scheduler",
                    "scheduler tick", "run now"),
        "say": "tick",
        "description": "Run exactly one scheduling tick through the scheduling layer.",
    },
    {
        "intent": INTENT_AUDIT,
        "keywords": ("audit", "chain", "ledger", "integrity", "tamper"),
        "phrases": ("audit log", "hash chain", "is the chain intact"),
        "say": "audit",
        "description": "Report the audit chain length and whether it verifies from genesis.",
    },
    {
        "intent": INTENT_OPPORTUNITIES,
        "keywords": ("opportunities", "opportunity", "opps", "opp"),
        "phrases": ("top opportunities", "best opportunities"),
        "say": "opportunities",
        "description": "Report the top scored opportunities and their status.",
    },
    {
        "intent": INTENT_BOTS,
        "keywords": ("bots", "bot", "verdicts", "verdict", "specs", "spec"),
        "phrases": ("list bots", "which bots"),
        "say": "bots",
        "description": "Report bot specs and their keep-or-kill verdicts.",
    },
    {
        "intent": INTENT_STATUS,
        "keywords": ("status", "counts", "count", "loop", "state", "states", "progress"),
        "phrases": ("what is the status", "what's the status", "loop status", "core loop",
                    "how many jobs", "how many signals"),
        "say": "status",
        "description": "Report the loop counts: jobs per pipeline state, signals, bots.",
    },
)

_WORD_RE = re.compile(r"[a-z0-9']+")


def normalize(transcript) -> str:
    """Lowercase, collapse whitespace, keep the words. Punctuation is dropped."""
    return " ".join(str(transcript or "").lower().split())


def tokens(transcript) -> list[str]:
    return _WORD_RE.findall(normalize(transcript))


def resolve_intent(transcript) -> str:
    """Deterministic keyword/phrase match. Unknown input -> ``not_understood``."""
    text = normalize(transcript)
    if not text:
        return INTENT_UNKNOWN
    words = set(tokens(text))
    # punctuation-free, space-padded copy for whole-phrase matching
    spaced = " " + " ".join(_WORD_RE.findall(text)) + " "
    for command in COMMANDS:
        for phrase in command["phrases"]:
            if f" {phrase} " in spaced:
                return command["intent"]
        if words & set(command["keywords"]):
            return command["intent"]
    return INTENT_UNKNOWN


def commands_document() -> dict:
    """The supported command list, served at GET /api/voice/commands."""
    return {
        "component": COMPONENT_NAME,
        "intents": list(INTENTS),
        "commands": [
            {
                "intent": c["intent"],
                "description": c["description"],
                "keywords": list(c["keywords"]),
                "phrases": list(c["phrases"]),
                "example": c["say"],
            }
            for c in COMMANDS
        ],
        "unknown_intent": INTENT_UNKNOWN,
        "matching": "deterministic keyword match; no model, no guessing",
        "transport": "browser Web Speech API (recognition + speechSynthesis)",
        "api_key_required": False,
        "audio_uploaded_to_server": False,
        "honesty": HONESTY,
    }


def _command_list_sentence() -> str:
    names = [c["say"] for c in COMMANDS]
    return "I can do: " + ", ".join(names[:-1]) + " and " + names[-1] + "."


# --------------------------------------------------------------------------
# reply builders — one per intent, each returns (reply, data)
# --------------------------------------------------------------------------

def _reply_status() -> tuple[str, dict]:
    from . import ingestion, measurement, opportunity, service

    counts = service.counts_by_state()
    total = sum(counts.values())
    parts = [
        f"{counts.get(state, 0)} {sm.STATE_LABELS.get(state, state).lower()}"
        for state in sm.PIPELINE_STATES
    ]
    chain = service.chain_status()
    signals = ingestion.signal_counts()
    opps = opportunity.counts()
    bots = measurement.counts()
    reply = (
        f"Loop status: {total} job{'s' if total != 1 else ''} — "
        + ", ".join(parts)
        + f". {signals['total']} signal{'s' if signals['total'] != 1 else ''} stored, "
        + f"{opps['total']} opportunit{'ies' if opps['total'] != 1 else 'y'} scored, "
        + f"{bots['measurements']} measurement{'s' if bots['measurements'] != 1 else ''} recorded. "
        + f"Audit chain {chain['length']} row{'s' if chain['length'] != 1 else ''}, "
        + ("intact." if chain["ok"] else f"BROKEN at row {chain['broken_at']}.")
    )
    return reply, {
        "counts": counts,
        "jobs_total": total,
        "pipeline": sm.PIPELINE_STATES,
        "terminal": [s for s in sm.ALL_STATES if s not in sm.PIPELINE_STATES],
        "signals": signals,
        "opportunities": {"total": opps["total"], "by_status": opps["by_status"]},
        "bots": bots,
        "chain": chain,
    }


def _reply_opportunities() -> tuple[str, dict]:
    from . import opportunity

    rows = opportunity.list_opportunities(limit=5)
    total = opportunity.counts()["total"]
    top = [
        {
            "id": r["id"],
            "title": r["title"],
            "composite_score": r.get("composite_score"),
            "status": r.get("status"),
            "verdict": r.get("verdict"),
        }
        for r in rows
    ]
    if not top:
        reply = (
            "No opportunities are stored yet. Run the opportunity engine — by voice say "
            "'tick' if the seeded opportunities schedule is due, or use POST "
            "/opportunities/run."
        )
    else:
        spoken = []
        for i, opp in enumerate(top[:3], start=1):
            spoken.append(
                f"{i}. {opp['title']} — score {opp['composite_score']}, status {opp['status']}"
            )
        reply = f"Top {len(top[:3])} of {total} opportunities: " + "; ".join(spoken) + "."
    return reply, {"opportunities": top, "count": total, "returned": len(top)}


def _reply_bots() -> tuple[str, dict]:
    from . import measurement

    bots = measurement.list_bots()
    rows = [
        {
            "id": b["id"],
            "bot_name": b.get("bot_name"),
            "status": b.get("status"),
            "verdict": b.get("current_verdict"),
            "reason": b.get("current_reason"),
            "risk_level": b.get("risk_level"),
            "has_measurement": b.get("latest_measurement") is not None,
        }
        for b in bots
    ]
    counts = measurement.counts()
    if not rows:
        reply = (
            "There are no bot specs yet. A spec is built from a VERIFIED opportunity "
            "(POST /api/bots/build); nothing is deployed."
        )
    else:
        spoken = []
        for b in rows[:3]:
            spoken.append(f"{b['bot_name']} is {b['verdict']}")
        reply = (
            f"{len(rows)} bot spec{'s' if len(rows) != 1 else ''}, none deployed: "
            + "; ".join(spoken)
            + f". Recorded decisions: {counts['decisions']}."
        )
    return reply, {"bots": rows, "count": len(rows), "counts": counts, "deployed": False}


def _reply_audit() -> tuple[str, dict]:
    state = audit.verify()
    head = audit.head()
    if state["ok"]:
        reply = (
            f"Audit chain intact: {state['length']} rows, verified from genesis to head "
            f"{state.get('head_hash') or head['row_hash']}."
        )
    else:
        reply = (
            f"Audit chain is BROKEN at row {state['broken_at']}: {state['reason']}. "
            f"{state['length']} rows checked."
        )
    return reply, {
        "ok": state["ok"],
        "length": state["length"],
        "broken_at": state["broken_at"],
        "reason": state["reason"],
        "first_broken_seq": state.get("first_broken_seq"),
        "head_hash": state.get("head_hash") or head["row_hash"],
        "head": head,
        "append_only": True,
    }


def _reply_tick() -> tuple[str, dict]:
    from . import scheduling

    result = scheduling.tick()
    fired = [
        {
            "schedule_id": f["schedule_id"],
            "name": f["name"],
            "target_kind": f["target_kind"],
            "outcome": f["outcome"],
            "summary": f["summary"],
        }
        for f in result["fired"]
    ]
    if fired:
        spoken = "; ".join(f"{f['name']} ({f['target_kind']}) {f['outcome']}" for f in fired)
        reply = (
            f"Scheduler tick fired {len(fired)} schedule{'s' if len(fired) != 1 else ''}: "
            f"{spoken}. Nothing fires on its own — this ran because you asked."
        )
    else:
        reply = (
            f"Scheduler tick: nothing was due. {result['enabled']} enabled "
            f"schedule{'s' if result['enabled'] != 1 else ''} waiting. "
            f"This is tick-driven: nothing runs on its own."
        )
    return reply, result


def _reply_help() -> tuple[str, dict]:
    reply = _command_list_sentence() + " Say one of those, or type it in the console."
    return reply, {"commands": commands_document()["commands"], "intents": list(INTENTS)}


def _reply_unknown(transcript: str) -> tuple[str, dict]:
    heard = (transcript or "").strip()
    reply = (
        (f"I didn't understand \"{heard}\". " if heard else "I didn't catch that. ")
        + _command_list_sentence()
        + " I won't guess."
    )
    return reply, {
        "commands": commands_document()["commands"],
        "heard": heard,
        "matched": False,
    }


_REPLIES = {
    INTENT_STATUS: _reply_status,
    INTENT_OPPORTUNITIES: _reply_opportunities,
    INTENT_BOTS: _reply_bots,
    INTENT_AUDIT: _reply_audit,
    INTENT_TICK: _reply_tick,
    INTENT_HELP: _reply_help,
}


# --------------------------------------------------------------------------
# the console
# --------------------------------------------------------------------------

def handle_command(transcript, *, write_audit: bool = True, source: str = "browser") -> dict:
    """Route one transcript through the existing orchestrator. Never raises.

    Returns ``{transcript, intent, reply, data, ok}``. ``reply`` is the exact text
    the browser should speak with ``speechSynthesis``.
    """
    text = str(transcript or "").strip()
    intent = resolve_intent(text)
    error = None

    try:
        if intent == INTENT_UNKNOWN:
            reply, data = _reply_unknown(text)
        else:
            reply, data = _REPLIES[intent]()
    except Exception as exc:  # a broken layer must not break the voice loop
        log.warning("voice intent %s failed: %s", intent, exc)
        error = f"{type(exc).__name__}: {exc}"
        reply = (
            f"That command was understood as {intent}, but it failed: {error}. "
            "Nothing was guessed and nothing else was changed."
        )
        data = {"error": error}

    result = {
        "transcript": text,
        "intent": intent,
        "reply": reply,
        "data": data,
        "ok": intent != INTENT_UNKNOWN and error is None,
        "understood": intent != INTENT_UNKNOWN,
        "error": error,
        "source": source,
    }

    if write_audit:
        try:
            row = audit.record(
                COMPONENT_NAME, "voice.command", "voice_command", None,
                {
                    "transcript": text,
                    "intent": intent,
                    "reply": reply,
                    "understood": intent != INTENT_UNKNOWN,
                    "ok": result["ok"],
                    "error": error,
                    "source": source,
                    "audio_uploaded": False,
                    "recognised_by": "browser Web Speech API",
                    "matching": "deterministic keyword match",
                },
            )
            result["audit_seq"] = row["seq"]
        except Exception as exc:  # pragma: no cover - the ledger is append-only
            log.warning("voice command could not be audited: %s", exc)
            result["audit_error"] = f"{type(exc).__name__}: {exc}"

    return result


# --------------------------------------------------------------------------
# the registry component (a tool: owns no pipeline state)
# --------------------------------------------------------------------------

class VoiceConsole:
    """Registered capability. Not a pipeline state — looked up by name."""

    name = COMPONENT_NAME

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

    def handle(self, job: dict) -> dict:
        transcript = (job or {}).get("transcript") or ""
        result = handle_command(transcript, source="registry")
        return {
            "to_state": None,  # a tool never transitions a job
            "note": f"voice command {result['intent']!r} -> {result['reply'][:160]}",
            "payload_patch": {},
            "data": {
                "intent": result["intent"],
                "reply": result["reply"],
                "understood": result["understood"],
            },
        }


def register_voice(registry) -> object:
    """Register the voice console 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=VoiceConsole(),
            description=(
                "Local voice console: deterministic intent routing over the existing layers "
                "(status / opportunities / bots / audit / tick / help). Audio never reaches "
                "the server; only the transcript does, and every command is audited."
            ),
            kind="tool",
        )
    )
