#!/usr/bin/env python3
"""
Bilingual (Mandarin + English) Live Diarized Storytelling Stream — PoC Runner.

Implements the Silent Cartographer architecture:
  - Zero unsolicited spoken audio output (0 dB client mute invariant)
  - Real-time bilingual Mandarin/English code-switch detection & entity/gap extraction
  - Single-cue peripheral Whisper Rail with dwell-time throttling (>= 75s default)
  - Structured session logging (session_events.jsonl) + A/B evaluation scorecard (scorecard.json)

Modes:
  1. --demo (zero API key, zero external packages):
     Replays the anonymized bilingual Mandarin/English fixture (`sample_session.jsonl`),
     runs deterministic code-switch + entity + cue-gap extraction and diarization evaluation,
     compares Silent Cartographer vs. counterfactual Interrupting Co-Host metrics,
     and writes `session_events.jsonl` and `scorecard.json`.

  2. --live (requires `google-genai >= 2.3.0` and `GEMINI_API_KEY`):
     Streams 16 kHz mono 16-bit PCM audio from a microphone (via optional `sounddevice`)
     or a 16 kHz WAV file (`--wav`) to the Gemini Live API using current SDK identifiers:
       - `--engine live-agent` (default): `gemini-3.8-live` with NON_BLOCKING function calls
         (`log_diarized_turn`, `emit_whisper_cue`), input/output audio transcription,
         sliding-window context compression, session resumption, GoAway handling,
         and a hard client-side 0 dB audio sink (never opens speaker playback).
       - `--engine transcribe`: `gemini-3.5-transcribe-live` (`response_modalities=["TEXT"]`)
         with automatic language detection (`language_codes=[]`), interim + finalized
         transcripts, and local deterministic cue-gap extraction.
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import re
import sys
import time
import wave
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterable

SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_SAMPLE = SCRIPT_DIR / "sample_session.jsonl"
DEFAULT_OUT_DIR = SCRIPT_DIR / "demo_output"

CJK_SPAN_RE = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf]+")
LATIN_SPAN_RE = re.compile(r"[A-Za-z][A-Za-z0-9'-]*")
YEAR_RE = re.compile(r"\b(19[5-9]\d|20[0-2]\d)\b")

# Curated bilingual anchor lexicons for deterministic offline / demo extraction.
PLACE_PATTERNS = [
    r"\bCedar Street\b",
    r"\bRiver Road\b",
    r"\bsouth side\b",
    r"\bstation overpass\b",
    r"早点铺",
    r"巷口",
    r"楼道",
]
TIME_PATTERNS = [
    r"\b19[5-9]\d\b",
    r"\b20[0-2]\d\b",
    r"\bFebruary\s+2000\b",
    r"\bFebruary\s+snowstorm\b",
    r"\bMid-Autumn Festival\b",
    r"冬天",
    r"春天",
    r"秋天",
    r"清晨五点钟",
]
PERSON_PATTERNS = [
    r"\bUncle Lin\b",
    r"房东阿姨",
    r"三楼邻居家小狗",
    r"二楼(?:刚来读书的)?学生",
    r"老板娘",
]
ARTIFACT_PATTERNS = [
    r"\bblue\s+bicycle\b",
    r"\bsecond-hand\s+bike\b",
    r"\bradiator\b",
    r"\bkerosene\s+heater\b",
    r"\bginger\s+soup\b",
    r"\broasted\s+sweet\s+potatoes\b",
    r"\blocal\s+paper\b",
    r"蓝单车",
    r"电饭锅",
    r"老槐树",
    r"红塑料凳",
    r"牛皮纸袋",
    r"车铃铛",
]
GAP_MARKERS = [
    "还是",
    "是不是",
    "什么时候",
    "吗？",
    "记串",
    "Wait",
    "or 2000",
    "uncertain",
]

SYSTEM_INSTRUCTION_SILENT_CARTOGRAPHER = """
You are a Silent Cartographer listening to a consented, bilingual Mandarin + English
family storytelling conversation between a Host and a Parent/Guest.

Strict room-footing invariants:
1. NEVER interrupt pauses or act as a speaking third participant. Prefer calling the
   non-blocking tools (`log_diarized_turn` and `emit_whisper_cue`) instead of speaking.
2. Preserve natural Mandarin-English code-switching verbatim without flattening either
   language into the other.
3. Track speaker turns conservatively (`Host` vs `Parent`) and extract time-scoped
   places, dates, people/roles, concrete sensory details, and unresolved gaps.
4. Emit `emit_whisper_cue` sparingly (at most once per 75 seconds) with a bare anchor
   label (<= 8 words, e.g. "1999 vs 2000? · Cedar St bakery"), NEVER a scripted
   interview question for the Host to read aloud.
""".strip()


@dataclass
class WhisperCueState:
    min_dwell_s: float = 75.0
    last_emit_t_s: float = -1e9
    active_cue: dict[str, Any] | None = None
    emitted_count: int = 0
    suppressed_by_dwell: int = 0

    def consider(
        self,
        t_s: float,
        candidate_anchor: str | None,
        gap_reason: str | None,
        confidence: float = 0.78,
        source: str = "deterministic",
    ) -> dict[str, Any] | None:
        if not candidate_anchor:
            return None
        elapsed = t_s - self.last_emit_t_s
        if elapsed < self.min_dwell_s:
            self.suppressed_by_dwell += 1
            return None
        cue = {
            "t_s": round(t_s, 2),
            "anchor": candidate_anchor,
            "reason": gap_reason or "peripheral memory anchor",
            "confidence": round(confidence, 2),
            "audio_db": 0,
            "source": source,
            "host_action_options": ["keep_in_reserve", "use_gently", "dismiss"],
        }
        self.last_emit_t_s = t_s
        self.active_cue = cue
        self.emitted_count += 1
        return cue


def detect_code_switches(text: str) -> dict[str, Any]:
    """Segment a bilingual utterance into CJK and Latin spans and count transitions."""
    tokens: list[tuple[int, str, str]] = []
    for m in CJK_SPAN_RE.finditer(text):
        tokens.append((m.start(), "zh", m.group(0)))
    for m in LATIN_SPAN_RE.finditer(text):
        tokens.append((m.start(), "en", m.group(0)))
    tokens.sort(key=lambda item: item[0])

    merged: list[dict[str, str]] = []
    for _, lang, seg in tokens:
        if merged and merged[-1]["lang"] == lang:
            sep = " " if lang == "en" else ""
            merged[-1]["text"] += sep + seg
        else:
            merged.append({"lang": lang, "text": seg})

    switches = max(0, len(merged) - 1)
    langs = {span["lang"] for span in merged}
    if langs == {"zh", "en"}:
        mix = "zh+en"
    elif "zh" in langs:
        mix = "zh"
    elif "en" in langs:
        mix = "en"
    else:
        mix = "other"

    cjk_chars = sum(len(m.group(0)) for m in CJK_SPAN_RE.finditer(text))
    latin_words = len(LATIN_SPAN_RE.findall(text))
    return {
        "language_mix": mix,
        "intra_turn_switches": switches,
        "cjk_chars": cjk_chars,
        "latin_words": latin_words,
        "spans": merged,
    }


def extract_entities_and_gaps(text: str) -> dict[str, Any]:
    """Deterministic bilingual entity and cue-gap extractor for offline / hybrid use."""
    found: list[dict[str, str]] = []
    seen: set[tuple[str, str]] = set()

    def scan(patterns: Iterable[str], etype: str) -> None:
        for pat in patterns:
            for match in re.finditer(pat, text, flags=re.IGNORECASE):
                val = match.group(0).strip()
                key = (val.lower(), etype)
                if key not in seen:
                    seen.add(key)
                    found.append({"text": val, "type": etype})

    scan(PLACE_PATTERNS, "place")
    scan(TIME_PATTERNS, "date_or_era")
    scan(PERSON_PATTERNS, "person_role")
    scan(ARTIFACT_PATTERNS, "artifact")

    years = sorted(set(YEAR_RE.findall(text)))
    has_gap_signal = any(marker.lower() in text.lower() for marker in GAP_MARKERS)

    candidate_anchor: str | None = None
    gap_reason: str | None = None
    if len(years) >= 2:
        candidate_anchor = f"{years[0]} vs {years[1]}? · timeline check"
        gap_reason = "two candidate years mentioned in same turn"
    elif has_gap_signal and found:
        top = found[0]["text"]
        candidate_anchor = f"Anchor: {top} (unconfirmed)"
        gap_reason = "open question or uncertainty marker near named entity"
    elif any(e["type"] == "place" for e in found) and any(e["type"] == "artifact" for e in found):
        place = next(e["text"] for e in found if e["type"] == "place")
        art = next(e["text"] for e in found if e["type"] == "artifact")
        candidate_anchor = f"{place} · {art}"
        gap_reason = "place + sensory artifact cluster (optional follow-up)"

    return {
        "entities": found,
        "years_mentioned": years,
        "has_gap_signal": has_gap_signal,
        "candidate_anchor": candidate_anchor,
        "gap_reason": gap_reason,
    }


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    with path.open("r", encoding="utf-8") as fh:
        for lineno, raw in enumerate(fh, start=1):
            line = raw.strip()
            if not line:
                continue
            try:
                records.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(f"Invalid JSON on line {lineno} of {path.name}: {exc}") from exc
    return records


def run_demo(sample_path: Path, out_dir: Path, dwell_s: float = 75.0, quiet: bool = False) -> dict[str, Any]:
    turns = load_jsonl(sample_path)
    out_dir.mkdir(parents=True, exist_ok=True)
    events_path = out_dir / "session_events.jsonl"
    scorecard_path = out_dir / "scorecard.json"

    controller = WhisperCueState(min_dwell_s=dwell_s)
    events: list[dict[str, Any]] = []

    correct_speaker = 0
    confusion_pairs: list[dict[str, Any]] = []
    parent_units = 0
    host_units = 0
    code_switched_turns = 0
    total_switches = 0
    total_cjk_chars = 0
    total_latin_words = 0
    total_episodic_details = 0
    unique_entities: set[tuple[str, str]] = set()
    open_gaps: list[str] = []
    long_pauses = 0
    cohost_interruptions = 0
    cohost_broken_pauses = 0

    for turn in turns:
        t_start = float(turn.get("t_start_s", 0.0))
        t_end = float(turn.get("t_end_s", t_start))
        ref_speaker = str(turn.get("speaker", "Unknown"))
        pred_speaker = str(turn.get("predicted_speaker", ref_speaker))
        pause_ms = int(turn.get("pause_before_ms", 0))
        text = str(turn.get("text", ""))

        if pred_speaker == ref_speaker:
            correct_speaker += 1
        else:
            confusion_pairs.append(
                {
                    "turn_id": turn.get("turn_id"),
                    "reference": ref_speaker,
                    "predicted": pred_speaker,
                    "reason": "short overlapping backchannel",
                }
            )

        cs = detect_code_switches(text)
        ext = extract_entities_and_gaps(text)

        # Approximate speaking-share units (CJK characters / 2 + Latin words).
        turn_units = round(cs["cjk_chars"] / 2.0 + cs["latin_words"], 1)
        if ref_speaker == "Parent":
            parent_units += turn_units
        elif ref_speaker == "Host":
            host_units += turn_units

        if cs["language_mix"] == "zh+en":
            code_switched_turns += 1
        total_switches += cs["intra_turn_switches"]
        total_cjk_chars += cs["cjk_chars"]
        total_latin_words += cs["latin_words"]

        details = list(turn.get("episodic_details") or [])
        total_episodic_details += len(details)

        merged_entities = {(e["text"].lower(), e["type"]) for e in ext["entities"]}
        for ent in turn.get("entities") or []:
            merged_entities.add((str(ent["text"]).lower(), str(ent["type"])))
        unique_entities.update(merged_entities)

        if turn.get("open_gap"):
            open_gaps.append(str(turn["open_gap"]))

        if pause_ms >= 2000:
            long_pauses += 1

        if turn.get("cohost_interruption"):
            cohost_interruptions += 1
            if pause_ms >= 2000:
                cohost_broken_pauses += 1

        expected_cue = turn.get("whisper_cue_expected")
        cue_anchor = expected_cue["anchor"] if isinstance(expected_cue, dict) else ext["candidate_anchor"]
        cue_reason = expected_cue["note"] if isinstance(expected_cue, dict) else ext["gap_reason"]

        # Only evaluate peripheral cues on Parent turns or explicit anchor candidates.
        emitted_cue = None
        if ref_speaker == "Parent" or isinstance(expected_cue, dict):
            emitted_cue = controller.consider(
                t_s=t_end,
                candidate_anchor=cue_anchor,
                gap_reason=cue_reason,
                confidence=0.82 if isinstance(expected_cue, dict) else 0.72,
                source="fixture_plus_deterministic",
            )

        event = {
            "event_type": "diarized_turn",
            "turn_id": turn.get("turn_id"),
            "t_start_s": t_start,
            "t_end_s": t_end,
            "pause_before_ms": pause_ms,
            "speaker_ref": ref_speaker,
            "speaker_pred": pred_speaker,
            "text": text,
            "gloss_en": turn.get("gloss_en", ""),
            "code_switch": cs,
            "extracted_entities": ext["entities"],
            "episodic_details": details,
            "open_gap": turn.get("open_gap"),
            "silent_cartographer_cue": emitted_cue,
            "counterfactual_cohost_interruption": turn.get("cohost_interruption"),
        }
        events.append(event)

    duration_s = max((float(t.get("t_end_s", 0.0)) for t in turns), default=0.0)
    duration_min = round(duration_s / 60.0, 2) if duration_s > 0 else 0.0

    scorecard = {
        "schema_version": "1.0",
        "mode": "demo",
        "data_origin": "synthetic_anonymized_fixture",
        "input_fixture": sample_path.name,
        "duration_seconds": duration_s,
        "duration_minutes": duration_min,
        "diarization": {
            "total_turns": len(turns),
            "speaker_accuracy": round(correct_speaker / len(turns), 4) if turns else 0.0,
            "correct_turns": correct_speaker,
            "parent_to_host_floor_ratio": round(parent_units / host_units, 2) if host_units else None,
            "confusions": confusion_pairs,
        },
        "bilingual_code_switching": {
            "code_switched_turns": code_switched_turns,
            "code_switched_share": round(code_switched_turns / len(turns), 4) if turns else 0.0,
            "total_intra_turn_switches": total_switches,
            "cjk_char_count": total_cjk_chars,
            "latin_word_count": total_latin_words,
        },
        "memory_yield": {
            "concrete_episodic_details": total_episodic_details,
            "episodic_details_per_min": round(total_episodic_details / duration_min, 2) if duration_min else 0.0,
            "unique_entities_tagged": len(unique_entities),
            "open_gaps_surfaced": len(open_gaps),
        },
        "room_discipline": {
            "long_pauses_over_2s": long_pauses,
            "silent_cartographer_spoken_interruptions": 0,
            "silent_cartographer_audio_output_db": 0,
            "silent_cartographer_cues_emitted": controller.emitted_count,
            "cues_suppressed_by_dwell_gate": controller.suppressed_by_dwell,
            "min_dwell_seconds": dwell_s,
            "counterfactual_cohost_interruptions": cohost_interruptions,
            "counterfactual_long_pauses_broken_pct": (
                round(100.0 * cohost_broken_pauses / long_pauses, 1) if long_pauses else 0.0
            ),
        },
        "caveat": (
            "Synthetic anonymized fixture evaluation only. Real Mandarin/English diarization "
            "accuracy and room comfort must be measured using the 45-minute counterbalanced "
            "A/B protocol in README.md."
        ),
    }

    with events_path.open("w", encoding="utf-8") as fh:
        for ev in events:
            fh.write(json.dumps(ev, ensure_ascii=False) + "\n")

    with scorecard_path.open("w", encoding="utf-8") as fh:
        json.dump(scorecard, fh, ensure_ascii=False, indent=2)
        fh.write("\n")

    if not quiet:
        print("=== Bilingual Storytelling Stream (--demo) ===")
        print(f"Fixture: {sample_path.name} ({len(turns)} turns, {duration_min:.2f} min, synthetic)")
        print(
            f"Diarization: {correct_speaker}/{len(turns)} turns "
            f"({scorecard['diarization']['speaker_accuracy'] * 100:.1f}%), "
            f"Parent:Host floor ratio = {scorecard['diarization']['parent_to_host_floor_ratio']}x"
        )
        print(
            f"Code-switching: {code_switched_turns}/{len(turns)} mixed zh+en turns, "
            f"{total_switches} intra-turn switches"
        )
        print(
            f"Memory yield: {total_episodic_details} concrete episodic details "
            f"({scorecard['memory_yield']['episodic_details_per_min']}/min), "
            f"{len(unique_entities)} unique entities, {len(open_gaps)} open gaps"
        )
        print(
            f"Silent Cartographer: 0 dB audio, 0 broken pauses, "
            f"{controller.emitted_count} peripheral cues emitted "
            f"({controller.suppressed_by_dwell} suppressed by {dwell_s:.0f}s dwell gate)"
        )
        print(
            f"Counterfactual Co-Host: {cohost_interruptions} spoken interruptions "
            f"({scorecard['room_discipline']['counterfactual_long_pauses_broken_pct']}% of >=2s pauses broken)"
        )
        print(f"Wrote: {events_path.name} and {scorecard_path.name}")

    return scorecard


def _load_wav_pcm16_chunks(wav_path: Path, chunk_ms: int = 100) -> Iterable[bytes]:
    with wave.open(str(wav_path), "rb") as wf:
        if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getframerate() != 16000:
            raise ValueError(
                f"{wav_path.name} must be 16 kHz, 16-bit signed PCM, mono "
                f"(got {wf.getframerate()} Hz, {wf.getsampwidth() * 8}-bit, {wf.getnchannels()} ch)."
            )
        frames_per_chunk = int(16000 * chunk_ms / 1000)
        while True:
            data = wf.readframes(frames_per_chunk)
            if not data:
                break
            yield data


async def run_live(args: argparse.Namespace) -> None:
    """
    Live streaming runner using the current `google-genai` SDK (>= 2.3.0).

    Supports two engines:
      - `live-agent` (default): `gemini-3.8-live` with NON_BLOCKING function calls,
        context window compression, session resumption, GoAway reconnect handling,
        and a hard client-side 0 dB audio sink (drops inline_data audio chunks).
      - `transcribe`: `gemini-3.5-transcribe-live` (`response_modalities=["TEXT"]`)
        with automatic language detection (`language_codes=[]`) and local cue gating.
    """
    if not os.environ.get("GEMINI_API_KEY"):
        raise SystemExit(
            "GEMINI_API_KEY is not set. Export your key before using --live, "
            "or run with --demo for zero-key offline replay."
        )

    try:
        from google import genai
        from google.genai import types
    except ImportError as exc:
        raise SystemExit(
            "Missing current SDK. Install with: pip install -U 'google-genai>=2.3.0'"
        ) from exc

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    events_path = out_dir / "session_events.jsonl"
    scorecard_path = out_dir / "scorecard.json"

    client = genai.Client(http_options={"api_version": "v1beta"})
    controller = WhisperCueState(min_dwell_s=args.dwell_seconds)
    start_wall = time.monotonic()
    resumption_handle: str | None = None
    recorded_events: list[dict[str, Any]] = []

    def append_event(event: dict[str, Any]) -> None:
        recorded_events.append(event)
        with events_path.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(event, ensure_ascii=False) + "\n")

    custom_vocab = [t.strip() for t in args.vocab.split(",") if t.strip()]

    if args.engine == "transcribe":
        model = args.model or "gemini-3.5-transcribe-live"
        config = types.LiveConnectConfig(
            response_modalities=["TEXT"],
            input_audio_transcription=types.AudioTranscriptionConfig(
                language_codes=[],  # Automatic multilingual + code-switch detection
                **({"custom_vocabulary": custom_vocab} if custom_vocab else {}),
            ),
        )
    else:
        model = args.model or "gemini-3.8-live"
        log_turn_decl = types.FunctionDeclaration(
            name="log_diarized_turn",
            description=(
                "Silently log one completed bilingual speaker turn with speaker role, "
                "verbatim transcript, extracted entities, and concrete episodic details."
            ),
            behavior="NON_BLOCKING",
            parameters={
                "type": "OBJECT",
                "properties": {
                    "speaker": {"type": "STRING", "enum": ["Host", "Parent", "Other"]},
                    "transcript": {"type": "STRING"},
                    "language_mix": {"type": "STRING", "enum": ["zh", "en", "zh+en"]},
                    "entities": {"type": "ARRAY", "items": {"type": "STRING"}},
                    "episodic_details": {"type": "ARRAY", "items": {"type": "STRING"}},
                },
                "required": ["speaker", "transcript"],
            },
        )
        whisper_cue_decl = types.FunctionDeclaration(
            name="emit_whisper_cue",
            description=(
                "Stage at most one brief, bare peripheral memory anchor (<= 8 words) "
                "for the Host rail only. Never write scripted questions."
            ),
            behavior="NON_BLOCKING",
            parameters={
                "type": "OBJECT",
                "properties": {
                    "anchor_label": {"type": "STRING"},
                    "gap_reason": {"type": "STRING"},
                    "confidence": {"type": "NUMBER"},
                },
                "required": ["anchor_label", "gap_reason"],
            },
        )
        config = types.LiveConnectConfig(
            response_modalities=[types.Modality.AUDIO],
            system_instruction=types.Content(
                parts=[types.Part(text=SYSTEM_INSTRUCTION_SILENT_CARTOGRAPHER)]
            ),
            input_audio_transcription=types.AudioTranscriptionConfig(
                **({"custom_vocabulary": custom_vocab} if custom_vocab else {})
            ),
            output_audio_transcription=types.AudioTranscriptionConfig(),
            context_window_compression=types.ContextWindowCompressionConfig(
                sliding_window=types.SlidingWindow()
            ),
            session_resumption=types.SessionResumptionConfig(handle=resumption_handle),
            tools=[types.Tool(function_declarations=[log_turn_decl, whisper_cue_decl])],
        )

    audio_queue: asyncio.Queue[bytes | None] = asyncio.Queue(maxsize=64)

    async def produce_audio() -> None:
        if args.wav:
            wav_path = Path(args.wav)
            for chunk in _load_wav_pcm16_chunks(wav_path, chunk_ms=100):
                await audio_queue.put(chunk)
                await asyncio.sleep(0.1)
            await audio_queue.put(None)
            return

        try:
            import sounddevice as sd
        except ImportError as exc:
            raise SystemExit(
                "Microphone streaming requires `sounddevice` (pip install sounddevice), "
                "or pass --wav <16khz_mono.wav> to stream a recorded WAV file."
            ) from exc

        loop = asyncio.get_running_loop()

        def callback(indata: bytes, _frames: int, _time_info: Any, status: Any) -> None:
            if status:
                print(f"[mic status] {status}", file=sys.stderr)
            loop.call_soon_threadsafe(audio_queue.put_nowait, bytes(indata))

        print("Consent check: confirm everyone in the room agreed before speaking. Press Ctrl+C to stop.")
        with sd.RawInputStream(
            samplerate=16000,
            blocksize=1600,  # 100ms chunks
            channels=1,
            dtype="int16",
            callback=callback,
        ):
            try:
                await asyncio.sleep(args.max_seconds)
            except asyncio.CancelledError:
                pass
            finally:
                await audio_queue.put(None)

    async def send_loop(session: Any) -> None:
        while True:
            chunk = await audio_queue.get()
            if chunk is None:
                await session.send_realtime_input(audio_stream_end=True)
                return
            await session.send_realtime_input(
                audio=types.Blob(data=chunk, mime_type="audio/pcm;rate=16000")
            )

    async def receive_loop(session: Any) -> None:
        nonlocal resumption_handle
        async for response in session.receive():
            now_s = round(time.monotonic() - start_wall, 2)

            # Handle session resumption tokens and GoAway warnings gracefully.
            if getattr(response, "session_resumption_update", None):
                upd = response.session_resumption_update
                if upd.resumable and upd.new_handle:
                    resumption_handle = upd.new_handle

            if getattr(response, "go_away", None):
                append_event(
                    {
                        "event_type": "go_away",
                        "t_s": now_s,
                        "time_left": str(response.go_away.time_left),
                        "resumption_handle_present": bool(resumption_handle),
                    }
                )

            # Silent Cartographer tool calls (gemini-3.8-live NON_BLOCKING tools).
            if getattr(response, "tool_call", None):
                fn_responses = []
                for fc in response.tool_call.function_calls:
                    fc_args = dict(fc.args or {})
                    if fc.name == "log_diarized_turn":
                        transcript = str(fc_args.get("transcript", ""))
                        cs = detect_code_switches(transcript)
                        append_event(
                            {
                                "event_type": "diarized_turn",
                                "t_s": now_s,
                                "speaker_pred": fc_args.get("speaker", "Unknown"),
                                "text": transcript,
                                "code_switch": cs,
                                "extracted_entities": fc_args.get("entities", []),
                                "episodic_details": fc_args.get("episodic_details", []),
                                "source": model,
                            }
                        )
                        result = {"logged": True}
                    elif fc.name == "emit_whisper_cue":
                        cue = controller.consider(
                            t_s=now_s,
                            candidate_anchor=str(fc_args.get("anchor_label", "")).strip(),
                            gap_reason=str(fc_args.get("gap_reason", "")).strip(),
                            confidence=float(fc_args.get("confidence", 0.75)),
                            source=model,
                        )
                        if cue:
                            append_event({"event_type": "whisper_cue", **cue})
                            print(f"\n[WHISPER RAIL · 0 dB · {now_s:5.1f}s] {cue['anchor']} ({cue['reason']})")
                        result = {"displayed": bool(cue), "dwell_gate_s": controller.min_dwell_s}
                    else:
                        result = {"ignored": fc.name}

                    fn_responses.append(
                        types.FunctionResponse(name=fc.name, id=fc.id, response=result)
                    )
                await session.send_tool_response(function_responses=fn_responses)

            content = getattr(response, "server_content", None)
            if not content:
                continue

            # 0 dB hardware-mute invariant: inspect parts, never open speaker playback.
            if getattr(content, "model_turn", None) and content.model_turn.parts:
                for part in content.model_turn.parts:
                    if getattr(part, "inline_data", None):
                        continue  # Intentionally discarded: Silent Cartographer emits 0 dB audio.

            # Interim hypotheses (transcribe engine; printed only if --show-interim).
            interim = getattr(content, "interim_input_transcription", None)
            if interim and interim.text and args.show_interim:
                print(f"\r[interim] {interim.text}", end="", flush=True)

            # Finalized input audio transcription.
            final_tx = getattr(content, "input_transcription", None)
            if final_tx and final_tx.text:
                text = final_tx.text.strip()
                if text:
                    cs = detect_code_switches(text)
                    ext = extract_entities_and_gaps(text)
                    cue = (
                        controller.consider(
                            t_s=now_s,
                            candidate_anchor=ext["candidate_anchor"],
                            gap_reason=ext["gap_reason"],
                            source="local_transcribe_gate",
                        )
                        if args.engine == "transcribe"
                        else None
                    )
                    append_event(
                        {
                            "event_type": "input_transcription",
                            "t_s": now_s,
                            "text": text,
                            "code_switch": cs,
                            "extracted_entities": ext["entities"],
                            "silent_cartographer_cue": cue,
                            "source": model,
                        }
                    )
                    if cue:
                        print(f"\n[WHISPER RAIL · 0 dB · {now_s:5.1f}s] {cue['anchor']} ({cue['reason']})")

    print(f"Connecting Silent Cartographer ({args.engine}: {model}, 0 dB audio sink)...")
    async with client.aio.live.connect(model=model, config=config) as session:
        producer = asyncio.create_task(produce_audio())
        sender = asyncio.create_task(send_loop(session))
        receiver = asyncio.create_task(receive_loop(session))
        try:
            await asyncio.gather(producer, sender)
            await asyncio.sleep(1.5)
        finally:
            receiver.cancel()
            for task in (producer, sender, receiver):
                if not task.done():
                    task.cancel()

    elapsed_s = round(time.monotonic() - start_wall, 2)
    live_scorecard = {
        "schema_version": "1.0",
        "mode": "live",
        "engine": args.engine,
        "model": model,
        "data_origin": "live_wav_stream" if args.wav else "live_microphone_stream",
        "duration_seconds": elapsed_s,
        "events_logged": len(recorded_events),
        "silent_cartographer_audio_output_db": 0,
        "silent_cartographer_cues_emitted": controller.emitted_count,
        "cues_suppressed_by_dwell_gate": controller.suppressed_by_dwell,
    }
    with scorecard_path.open("w", encoding="utf-8") as fh:
        json.dump(live_scorecard, fh, ensure_ascii=False, indent=2)
        fh.write("\n")
    print(f"Session closed cleanly ({elapsed_s}s). Wrote {events_path.name} and {scorecard_path.name}.")


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        description="Bilingual (Mandarin + English) Silent Cartographer storytelling stream runner."
    )
    mode = p.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--demo",
        action="store_true",
        help="Run zero-key offline replay & evaluation on sample_session.jsonl.",
    )
    mode.add_argument(
        "--live",
        action="store_true",
        help="Stream live microphone or 16 kHz WAV audio to Gemini Live API (0 dB silent mode).",
    )
    p.add_argument(
        "--input",
        type=Path,
        default=DEFAULT_SAMPLE,
        help="Input JSONL fixture for --demo (default: sample_session.jsonl).",
    )
    p.add_argument(
        "--out-dir",
        type=Path,
        default=DEFAULT_OUT_DIR,
        help="Output directory for session_events.jsonl and scorecard.json.",
    )
    p.add_argument(
        "--dwell-seconds",
        type=float,
        default=75.0,
        help="Minimum seconds between peripheral Whisper Rail cues (default: 75).",
    )
    p.add_argument(
        "--engine",
        choices=["live-agent", "transcribe"],
        default="live-agent",
        help="Live API engine: gemini-3.8-live silent tools (`live-agent`) or gemini-3.5-transcribe-live (`transcribe`).",
    )
    p.add_argument(
        "--model",
        type=str,
        default="",
        help="Optional Gemini Live model override.",
    )
    p.add_argument(
        "--wav",
        type=Path,
        default=None,
        help="Optional 16 kHz mono 16-bit PCM WAV file to stream in --live mode instead of live mic.",
    )
    p.add_argument(
        "--vocab",
        type=str,
        default="Cedar Street,River Road,Mid-Autumn Festival",
        help="Comma-separated custom_vocabulary biasing terms (<= 100 recommended).",
    )
    p.add_argument(
        "--max-seconds",
        type=float,
        default=900.0,
        help="Safety timeout for live mic capture in seconds (default: 900 = 15 min block).",
    )
    p.add_argument(
        "--show-interim",
        action="store_true",
        help="Display interim transcripts in terminal (off by default to avoid screen-magnet gaze theft).",
    )
    p.add_argument("--quiet", action="store_true", help="Suppress stdout summary in --demo mode.")
    return p


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    if args.demo:
        run_demo(args.input, args.out_dir, dwell_s=args.dwell_seconds, quiet=args.quiet)
        return 0
    asyncio.run(run_live(args))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
