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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
"""StreamingBench JSON 协议下的统一推理脚本.

支持三个子任务:
  - SQA            : 4 选 1 MCQ, 同视频 5 个 question 顺序串联 (oracle history)
  - Contextual MCU : 4 选 1 MCQ (Misleading)
  - Contextual ACU : 4 选 1 MCQ (Anomaly)
  - Proactive PO   : 1s grid 流式 yes/no 触发检测

公共逻辑 (对齐 OVO-Bench Forward):
  - 每个 sample (= 1 video) 已建好 hypergraph
  - 每个 question 按 q.time_stamp_sec 严格截断 hypergraph: fact / episode 必须 end ≤ ts
  - 不切视频 (方案 A: 建图阶段 max_seconds 早停)
  - 推理时 LLM 看到的全是 ts 之前的事实, 绝不泄漏未来

OPENAI_API_KEY 必须由调用方提供.
"""
from __future__ import annotations

import argparse
import asyncio
import json
import logging
import os
import re
import sys
import time
from typing import Dict, List, Optional, Tuple

sys.path.insert(0, "/mnt/tokyo-ai/gst/GST_EGOSERVE/VideoRAG-algorithm")

# import ovobench 之前先尝试复用其 hardcoded key (ovobench main() 会在自身入口设置,
# 但作为 module import 时不会触发 main; 这里给一个 fallback 让 import 期不要 raise).
# 实际 OPENAI key 校验放到 main() 入口.
from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config2  # noqa: E402
from hypervideo.forward_dataset_loaders import (  # noqa: E402
    load_streamingbench_sqa_json,
    load_streamingbench_proactive_json,
    load_streamingbench_contextual_json,
)

logger = logging.getLogger("sb_eval")
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")


# ======================================================================
# 时间解析 / hypergraph 截断
# ======================================================================

def _parse_temporal_to_sec(s: str) -> float:
    """fact.temporal 形如 'DAY1-00:00:12' / '1-00:00:12' / 'HH:MM:SS' → 相对视频起点的秒.

    我们 hypergraph 里 day_num=1, start_seconds=0 起点.
    """
    if not s:
        return 0.0
    m = re.search(r"(\d+):(\d+):(\d+)(?:\.(\d+))?", s)
    if not m:
        return 0.0
    h, mn, sc = int(m.group(1)), int(m.group(2)), int(m.group(3))
    frac = float(f"0.{m.group(4)}") if m.group(4) else 0.0
    return h * 3600 + mn * 60 + sc + frac


def _truncate_hypergraph(hg: dict, t_cutoff_sec: float) -> Tuple[List[dict], List[dict]]:
    """按 t_cutoff_sec 严格截断 hypergraph (绝不泄漏未来):
      - episode: 必须 end_seconds ≤ t_cutoff (完整结束在 ts 之前才进 prompt)
        episode 跨越 ts 的话直接丢弃 — 用 frame_caption 补足 [last_ep_end, ts] 边界信息
      - fact: temporal_sec ≤ t_cutoff

    注: 因为我们建图时已经早停 (max_seconds = max(q.ts)), 同一 sample 多个 q
    共享一张超图. q.ts < max_seconds 时, hypergraph 里会有 ts 之后的 fact —— 必须
    在这里严格过滤.
    """
    eps = []
    for ep in hg.get("episodes", {}).values():
        start = ep.get("start_seconds", 0.0)
        end = ep.get("end_seconds", start + 1)
        if end <= t_cutoff_sec + 1e-6:
            eps.append(ep)
        # 跨越 ts 或完全在 ts 之后 → 跳过
    eps.sort(key=lambda x: x.get("start_seconds", 0.0))

    facts = []
    for f in hg.get("facts", {}).values():
        t = _parse_temporal_to_sec(f.get("temporal", ""))
        if t <= t_cutoff_sec + 1e-6:
            facts.append((t, f))
    facts.sort(key=lambda x: x[0])
    return eps, [f for _, f in facts]


def _filter_frame_captions(
    all_captions: List[dict],
    t_cutoff_sec: float,
    last_ep_end_sec: float = 0.0,
    max_seconds_back: float = 30.0,
) -> List[dict]:
    """从 frame_captions.json 取边界 caption: [max(last_ep_end, ts - max_seconds_back), ts].

    用途: episode 严格截断到 last_ep_end (≤ ts), 之后到 ts 之间的视觉信息靠 frame_caption
    补足 (类似 OVO-Bench 直接用 frame_caption 的做法).
    """
    out = []
    lower = max(last_ep_end_sec, t_cutoff_sec - max_seconds_back)
    for fc in all_captions:
        ts = fc.get("time_span", "")
        # time_span 形如 "1-00:00:10-00:00:12" 或 "DAY1-..."
        # 用结尾时间判断
        # 简化: 取最后一个 H:MM:SS 当 caption 结束时间
        all_t = re.findall(r"(\d+):(\d+):(\d+)", ts)
        if not all_t:
            continue
        last = all_t[-1]
        cap_end = int(last[0]) * 3600 + int(last[1]) * 60 + int(last[2])
        if lower <= cap_end <= t_cutoff_sec + 1e-6:
            out.append(fc)
    return out


def _format_frame_captions(caps: List[dict], max_each: int = 250) -> str:
    if not caps:
        return "(no recent frame captions)"
    lines = []
    for c in caps[-15:]:  # 最多 15 条避免过长
        cap = c.get("caption") or c.get("dense_caption") or c.get("description", "")
        lines.append(f"[{c.get('time_span','?')}] {str(cap)[:max_each]}")
    return "\n".join(lines)


def _format_episodes(eps: List[dict], max_each_desc: int = 600) -> str:
    if not eps:
        return "(no completed episodes yet)"
    out = []
    for ep in eps:
        out.append(
            f"[{ep.get('time_span','?')}] {ep.get('subject','')[:80]}\n"
            f"  summary: {(ep.get('summary','') or '')[:300]}\n"
            f"  description: {(ep.get('episode_description','') or '')[:max_each_desc]}"
        )
    return "\n".join(out)


def _format_facts(facts: List[dict], max_each: int = 200) -> str:
    if not facts:
        return "(no facts)"
    return "\n".join(
        f"[{f.get('temporal','?')}] {f.get('content','')[:max_each]}" for f in facts
    )


def _parse_json_response(r) -> Optional[dict]:
    if not r:
        return None
    if isinstance(r, dict):
        return r
    s = str(r)
    m = re.search(r"\{.*\}", s, re.DOTALL)
    if m:
        try:
            return json.loads(m.group())
        except Exception:
            pass
    return None


# ======================================================================
# Prompt 模板
# ======================================================================

# 三种推理 mode:
#   dump_all  : episode 全 (≤ ts) + fact 全 (≤ ts) + boundary frame_captions, 单次答
#   ep_retrieve: 只给 episode 全 + boundary captions, 让 LLM 自行决定是否检索 (1次机会)
#   agentic   : 同上但 prompt 风格更"自主" — 鼓励 LLM 必要时再检索, 对 fact 用 hierarchical 检索
#
# 共同基础: episode 严格 end ≤ ts, frame_caption 补 [last_ep_end, ts] 边界

MCQ_PROMPT_DUMP_ALL = """You are answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time.

QUESTION: {question}

OPTIONS:
{options_block}

VIDEO MEMORY (chronological, truncated to TIME = {qtime}):

EPISODES (subject + summary + description, only episodes that completed before {qtime}):
{episodes}

FACTS (atomic events ≤ {qtime}):
{facts}

RECENT FRAME CAPTIONS (boundary frames between the last completed episode and {qtime}, useful for the very latest visual state):
{frame_captions}

{prev_qa_block}

Pick the BEST option based ONLY on evidence at or before {qtime}. Do NOT use future content.

Output JSON: {{"answer": "A"|"B"|"C"|"D", "reasoning": "<one sentence>"}}
Output ONLY the JSON.
"""


MCQ_PROMPT_EP_RETRIEVE_ROUND1 = """You are answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time.

QUESTION: {question}

OPTIONS:
{options_block}

VIDEO MEMORY (chronological, truncated to TIME = {qtime}):

EPISODES (subject + summary + description, only episodes that completed before {qtime}):
{episodes}

RECENT FRAME CAPTIONS (boundary frames between last episode end and {qtime}):
{frame_captions}

{prev_qa_block}

You may ALSO retrieve atomic facts from the hypergraph if the episodes/captions above are NOT enough to answer confidently.

Decide:
  - If the episodes + frame captions clearly support one option → directly answer with decision="answer".
  - If you need more evidence (e.g. specific entity / count / cross-time detail) → decision="need_retrieval", give a focused retrieval_query.

Output JSON STRICTLY:
{{
  "decision": "answer" | "need_retrieval",
  "answer": "A"|"B"|"C"|"D" | null,
  "retrieval_query": "<empty if decision=answer; specific keywords / entities if need_retrieval>",
  "reasoning": "<one sentence>"
}}

Output ONLY the JSON.
"""


MCQ_PROMPT_EP_RETRIEVE_ROUND2 = """You are giving the FINAL answer after retrieval.

QUESTION (asked at TIME = {qtime}): {question}

OPTIONS:
{options_block}

ORIGINAL EPISODES (≤ {qtime}):
{episodes}

ORIGINAL RECENT FRAME CAPTIONS:
{frame_captions}

RETRIEVED FACTS (this round, filtered to ≤ {qtime}):
{retrieved_facts}

{prev_qa_block}

Pick the BEST option. You MUST output an answer letter now (no more retrieval).

Output JSON: {{"answer": "A"|"B"|"C"|"D", "reasoning": "<one sentence>"}}
Output ONLY the JSON.
"""


MCQ_PROMPT_AGENTIC_ROUND1 = """You are an agent answering a multi-choice question about a third-person video. The question is asked at TIME = {qtime} (absolute video time). You can ONLY use information up to that time.

QUESTION: {question}

OPTIONS:
{options_block}

You have access to a video memory hypergraph (Topic ⊂ Episode ⊂ Fact) and frame captions. The following minimal context is provided:

EPISODES (≤ {qtime}, only those fully completed):
{episodes}

RECENT FRAME CAPTIONS (boundary):
{frame_captions}

{prev_qa_block}

Two paths:
  (a) If the episodes + recent captions clearly answer the question → decision="answer".
  (b) If you genuinely need more evidence (specific entity, count, fine-grained action, anomaly detail) → decision="need_retrieval"; provide a focused retrieval_query that names the entity / event you need.

Be efficient: only retrieve when episodes are not specific enough. Don't retrieve to "double check" things that are already obvious from episodes.

Output JSON STRICTLY:
{{
  "decision": "answer" | "need_retrieval",
  "answer": "A"|"B"|"C"|"D" | null,
  "retrieval_query": "<empty | focused query>",
  "reasoning": "<one sentence>"
}}

Output ONLY the JSON.
"""


PO_TRIGGER_PROMPT = """You are watching a third-person video moment by moment. A user asked you the following trigger question earlier in the video; you must decide RIGHT NOW whether the trigger condition has just become true, so you should produce the literal output.

QUESTION (asked at {ask_time}): {question}

EXPECTED OUTPUT: "{gt_output}"

CURRENT TIME: {now_time} (absolute video time). You can ONLY use evidence from [video start, NOW].

VIDEO MEMORY (chronological, truncated to NOW):

EPISODES (only those fully completed before NOW):
{episodes}

FACTS (atomic events ≤ NOW, last 15s):
{facts}

RECENT FRAME CAPTIONS (boundary frames between last completed episode and NOW — primary signal for trigger detection):
{frame_captions}

PREVIOUS_DECISIONS at earlier grid points (your own past answers — do NOT repeat triggering if you already triggered):
{prev_decisions}

Decide: is THIS the right moment to output "{gt_output}"?
- Output "yes" only when the trigger condition described in QUESTION has just become true in the most recent frames AND you have not already triggered for it.
- Otherwise output "no".

Output JSON: {{"decision": "yes"|"no", "reasoning": "<one sentence citing the most recent fact / caption>"}}
Output ONLY the JSON.
"""


# ======================================================================
# MCQ 子任务 (SQA + Contextual)
# ======================================================================

def _format_options_block(opts: List[str]) -> str:
    if not opts:
        return ""
    if isinstance(opts[0], str) and opts[0][:2] in ("A.", "B.", "C.", "D."):
        # contextual: 已带 'A. ' 前缀
        return "\n".join(opts)
    return "\n".join(f"{chr(65+i)}. {o}" for i, o in enumerate(opts))


def _format_prev_qa_block_sqa(prev: List[dict]) -> str:
    """SQA oracle history: 把同 sample 已答的 question + GT_answer 拼进 prompt.

    官方协议要求把 GT 答案当 context 注入. 这里我们用 oracle GT (论文常用做法).
    """
    if not prev:
        return ""
    lines = ["PREVIOUS Q&A (same video, earlier moments — use as context for this question):"]
    for p in prev:
        opts = _format_options_block(p["options"])
        lines.append(
            f"  At {p['time_stamp']}, Q: {p['question']}\n"
            f"  Options:\n{_indent(opts, 4)}\n"
            f"  GT answer: {p['answer']}"
        )
    return "\n".join(lines) + "\n"


def _indent(s: str, n: int) -> str:
    pad = " " * n
    return "\n".join(pad + line for line in s.split("\n"))


async def _llm_call_raw(prompt: str) -> str:
    """调一次 gpt-5-mini, 返回原 response 字符串/dict."""
    try:
        resp = await gpt5_2_llm_config2.best_model_func_raw(
            gpt5_2_llm_config2.best_model_name,
            prompt,
            system_prompt=None,
            history_messages=[],
        )
        return resp
    except Exception as e:
        return f"__ERR__: {e}"


def _extract_letter(resp) -> Tuple[str, str]:
    """从 LLM response 抽 A/B/C/D + reasoning."""
    pj = _parse_json_response(resp)
    if pj:
        a = (pj.get("answer", "") or "").strip().upper()
        if a and a[0] in "ABCD":
            return a[0], pj.get("reasoning", "")
    m = re.search(r"\b([ABCD])\b", str(resp).upper())
    return (m.group(1) if m else "?", "fallback regex")


def _extract_decision_or_letter(resp) -> Tuple[str, dict]:
    """两阶段 prompt 的 round1 解析: 返回 (status, payload).
       status='answer'  → payload = {'answer','reasoning'}
       status='retrieve' → payload = {'retrieval_query','reasoning'}
       status='?'        → payload = {'reasoning': fallback}
    """
    pj = _parse_json_response(resp)
    if pj:
        d = (pj.get("decision", "") or "").strip().lower()
        if d == "answer":
            a = (pj.get("answer", "") or "").strip().upper()
            if a and a[0] in "ABCD":
                return "answer", {"answer": a[0], "reasoning": pj.get("reasoning", "")}
        if d == "need_retrieval":
            return "retrieve", {
                "retrieval_query": pj.get("retrieval_query", ""),
                "reasoning": pj.get("reasoning", ""),
            }
    # fallback: 试着直接抽字母
    m = re.search(r"\b([ABCD])\b", str(resp).upper())
    if m:
        return "answer", {"answer": m.group(1), "reasoning": "fallback regex"}
    return "?", {"reasoning": str(resp)[:120]}


def _last_episode_end(eps: List[dict]) -> float:
    if not eps:
        return 0.0
    return max(ep.get("end_seconds", ep.get("start_seconds", 0)) for ep in eps)


async def _retrieve_facts(
    hyper_vg, query: str, t_cutoff_sec: float, mode: str = "fact_only", top_k: int = 12,
) -> str:
    """走 HyperVideoGraph 的双索引检索 (BM25+语义 RRF). cutoff_ts 用 day1-HH:MM:SS 格式.

    返回格式化好的字符串 (含 retrieved facts).
    """
    cutoff_ts = (
        f"DAY1-{int(t_cutoff_sec//3600):02d}:{int((t_cutoff_sec%3600)//60):02d}:"
        f"{int(t_cutoff_sec%60):02d}"
    )
    try:
        ret = await hyper_vg.retrieve(query, cutoff_ts, mode=mode)
        return hyper_vg.format_retrieval_for_llm(ret)
    except Exception as e:
        return f"(retrieval error: {e})"


def evaluate_mcq_sample(
    item: dict,
    hg: dict,
    is_sqa: bool,
    prev_results: dict,
    mode: str = "dump_all",
    all_frame_captions: Optional[List[dict]] = None,
    hyper_vg=None,  # for retrieval modes
) -> Dict[str, dict]:
    """对 sample 内所有 question 推理.

    mode:
      - "dump_all": 全 fact + 全 episode + boundary frame_caption, 1 次 LLM
      - "ep_retrieve": 只 episode + boundary, LLM 决定是否检索 fact (1 次机会)
      - "agentic": 同 ep_retrieve 但 prompt 更"自主", 鼓励有节制地检索
    """
    out = {}
    qs = item["questions_list"]
    qs_sorted = sorted(qs, key=lambda q: q["time_stamp_sec"])
    prev_qa_for_sqa: List[dict] = []
    all_frame_captions = all_frame_captions or []

    for q in qs_sorted:
        qid = q["qid"]
        if qid in prev_results and prev_results[qid].get("answer") is not None:
            out[qid] = prev_results[qid]
            if is_sqa:
                prev_qa_for_sqa.append({
                    "time_stamp": q["time_stamp"], "question": q["question"],
                    "options": q["options"], "answer": q["answer"],
                })
            continue

        ts = q["time_stamp_sec"]
        eps, facts = _truncate_hypergraph(hg, ts)
        last_ep_end = _last_episode_end(eps)
        boundary_caps = _filter_frame_captions(all_frame_captions, ts, last_ep_end_sec=last_ep_end)
        eps_str = _format_episodes(eps)
        caps_str = _format_frame_captions(boundary_caps)
        opts_block = _format_options_block(q["options"])
        prev_qa_block = _format_prev_qa_block_sqa(prev_qa_for_sqa) if is_sqa else ""

        used_retrieval = False
        retrieved_text = ""
        retrieval_query = ""

        if mode == "dump_all":
            facts_str = _format_facts(facts)
            prompt = MCQ_PROMPT_DUMP_ALL.format(
                qtime=q["time_stamp"], question=q["question"],
                options_block=opts_block, episodes=eps_str, facts=facts_str,
                frame_captions=caps_str, prev_qa_block=prev_qa_block,
            )
            resp = asyncio.run(_llm_call_raw(prompt))
            pred, reason = _extract_letter(resp)

        elif mode in ("ep_retrieve", "agentic"):
            # Round 1: 给 episode + boundary, 让 LLM 决定
            tmpl = MCQ_PROMPT_AGENTIC_ROUND1 if mode == "agentic" else MCQ_PROMPT_EP_RETRIEVE_ROUND1
            prompt1 = tmpl.format(
                qtime=q["time_stamp"], question=q["question"],
                options_block=opts_block, episodes=eps_str,
                frame_captions=caps_str, prev_qa_block=prev_qa_block,
            )
            resp1 = asyncio.run(_llm_call_raw(prompt1))
            status, payload = _extract_decision_or_letter(resp1)

            if status == "answer":
                pred, reason = payload["answer"], payload["reasoning"]
            elif status == "retrieve" and hyper_vg is not None:
                used_retrieval = True
                retrieval_query = payload.get("retrieval_query", "") or q["question"]
                # hierarchical 模式利用 topic→ep→fact 三层约束 (agentic 用); ep_retrieve 用 fact_only
                ret_mode = "hierarchical" if mode == "agentic" else "fact_only"
                retrieved_text = asyncio.run(
                    _retrieve_facts(hyper_vg, retrieval_query, ts, mode=ret_mode)
                )
                # Round 2: 给 retrieved facts 强制答
                prompt2 = MCQ_PROMPT_EP_RETRIEVE_ROUND2.format(
                    qtime=q["time_stamp"], question=q["question"],
                    options_block=opts_block, episodes=eps_str,
                    frame_captions=caps_str, retrieved_facts=retrieved_text,
                    prev_qa_block=prev_qa_block,
                )
                resp2 = asyncio.run(_llm_call_raw(prompt2))
                pred, reason = _extract_letter(resp2)
                reason = f"[after retrieval: {retrieval_query[:60]}] {reason}"
            else:
                # 解析失败兜底: 用全 fact dump 重答一次
                facts_str = _format_facts(facts)
                fallback_prompt = MCQ_PROMPT_DUMP_ALL.format(
                    qtime=q["time_stamp"], question=q["question"],
                    options_block=opts_block, episodes=eps_str, facts=facts_str,
                    frame_captions=caps_str, prev_qa_block=prev_qa_block,
                )
                resp_fb = asyncio.run(_llm_call_raw(fallback_prompt))
                pred, reason = _extract_letter(resp_fb)
                reason = f"[r1 parse fail; dump-all fallback] {reason}"
        else:
            raise ValueError(f"未知 mode: {mode}")

        gt = q["answer"]
        ok = (pred == gt)
        out[qid] = {
            "answer": pred, "gt": gt, "ok": ok, "reasoning": reason,
            "time_stamp": q["time_stamp"], "mode": mode,
            "used_retrieval": used_retrieval, "retrieval_query": retrieval_query,
        }

        if is_sqa:
            prev_qa_for_sqa.append({
                "time_stamp": q["time_stamp"], "question": q["question"],
                "options": q["options"], "answer": q["answer"],
            })

    return out


# ======================================================================
# Proactive Output 1s grid 流式
# ======================================================================

async def _llm_answer_po(prompt: str) -> Tuple[str, str]:
    try:
        resp = await gpt5_2_llm_config2.best_model_func_raw(
            gpt5_2_llm_config2.best_model_name,
            prompt,
            system_prompt=None,
            history_messages=[],
        )
        pj = _parse_json_response(resp)
        if pj:
            d = (pj.get("decision", "") or "").strip().lower()
            if d in ("yes", "no"):
                return d, pj.get("reasoning", "")
        # fallback
        s = str(resp).lower()
        if "yes" in s.split()[:5] if s.split() else False:
            return "yes", "fallback substring"
        return "no", f"fallback default no: {str(resp)[:60]}"
    except Exception as e:
        return "no", f"err: {e}"


def _format_prev_decisions(prev: List[dict]) -> str:
    if not prev:
        return "(no prior grid points yet)"
    lines = []
    for p in prev[-6:]:  # 只取最近 6 个 grid 点, 避免 prompt 超长
        lines.append(f"  t={p['t']:.0f}s: {p['decision']} ({p['reasoning'][:80]})")
    return "\n".join(lines)


def evaluate_po_sample(
    item: dict,
    hg: dict,
    prev_results: dict,
    all_frame_captions: Optional[List[dict]] = None,
) -> Dict[str, dict]:
    """对 PO sample 内每个 question 流式 grid 1s 检测.

    截断规则 (与 SQA/Ctx 一致):
      - episode: 必须 end ≤ t_now (严格)
      - fact: temporal ≤ t_now
      - frame_caption: [last_ep_end, t_now] 边界 (补 episode 截断后的边界视觉)

    Returns: {qid: {answered_time_sec, gt_time_sec, gt_output, decisions: [...]}}
    """
    out = {}
    qs = item["questions_list"]
    test_info = item["test_info"]
    all_frame_captions = all_frame_captions or []

    grids_by_qid: Dict[str, List[dict]] = {}
    for ti in test_info:
        grids_by_qid.setdefault(ti["qid"], []).append(ti)

    for q in qs:
        qid = q["qid"]
        if qid in prev_results and prev_results[qid].get("done"):
            out[qid] = prev_results[qid]
            continue
        grids = sorted(grids_by_qid.get(qid, []), key=lambda x: x["realtime"])
        ask_t = q["time_stamp_sec"]
        gt_t = q.get("ground_truth_time_stamp_sec", ask_t + 1)
        gt_output = q.get("ground_truth_output", "")

        decisions: List[dict] = []
        answered_time = None

        for ti in grids:
            t_now = ti["realtime"]
            eps, facts = _truncate_hypergraph(hg, t_now)
            # 只展示最近的 episode (避免 prompt 过长)
            eps_recent = eps[-3:]
            last_ep_end = _last_episode_end(eps_recent)
            # 只展示最近 15s 内的 fact (PO 高度依赖最新视觉)
            facts_recent = [f for f in facts if _parse_temporal_to_sec(f.get("temporal", "")) >= t_now - 15.0]
            if not facts_recent and facts:
                facts_recent = facts[-10:]
            # frame_caption 补足 [last_ep_end, t_now] 边界
            boundary_caps = _filter_frame_captions(
                all_frame_captions, t_now,
                last_ep_end_sec=last_ep_end, max_seconds_back=15.0,
            )

            prompt = PO_TRIGGER_PROMPT.format(
                ask_time=q["time_stamp"],
                question=q["question"],
                gt_output=gt_output,
                now_time=f"{t_now:.0f}s",
                episodes=_format_episodes(eps_recent, max_each_desc=300),
                facts=_format_facts(facts_recent),
                frame_captions=_format_frame_captions(boundary_caps),
                prev_decisions=_format_prev_decisions(decisions),
            )
            decision, reason = asyncio.run(_llm_answer_po(prompt))
            decisions.append({"t": t_now, "decision": decision, "reasoning": reason})

            if decision == "yes":
                answered_time = t_now
                break

        out[qid] = {
            "qid": qid,
            "ask_time_sec": ask_t,
            "gt_time_sec": gt_t,
            "gt_output": gt_output,
            "answered_time_sec": answered_time,
            "answered": answered_time is not None,
            "abs_offset_sec": (abs(answered_time - gt_t) if answered_time is not None else None),
            "decisions": decisions,
            "n_grids": len(decisions),
            "done": True,
        }

    return out


# ======================================================================
# 主入口
# ======================================================================

def _load_dataset_for(name: str) -> List[dict]:
    if name == "sqa":
        return load_streamingbench_sqa_json()
    if name == "contextual":
        return load_streamingbench_contextual_json()
    if name == "proactive":
        return load_streamingbench_proactive_json()
    raise ValueError(f"未知 dataset: {name}")


def _score_mcq(out: Dict[str, Dict[str, dict]]) -> dict:
    """汇总 MCQ 结果."""
    n_total = 0; n_correct = 0
    by_subtype: Dict[str, dict] = {}
    for sid, qresults in out.items():
        for qid, r in qresults.items():
            if "answer" not in r:
                continue
            n_total += 1
            if r.get("ok"):
                n_correct += 1
            # 按 sample id 前缀分 mcu/acu
            tag = "all"
            if sid.startswith("mcu_"):
                tag = "mcu"
            elif sid.startswith("acu_"):
                tag = "acu"
            by_subtype.setdefault(tag, {"correct": 0, "total": 0})
            by_subtype[tag]["total"] += 1
            if r.get("ok"):
                by_subtype[tag]["correct"] += 1
    summary = {
        "total": n_total,
        "correct": n_correct,
        "acc": (100 * n_correct / n_total) if n_total else 0,
        "by_subtype": {
            k: {"acc": (100 * v["correct"] / v["total"]) if v["total"] else 0, **v}
            for k, v in by_subtype.items()
        },
    }
    return summary


def _score_po(out: Dict[str, Dict[str, dict]]) -> dict:
    """PO 评分: 多个偏差容忍窗口."""
    n_total = 0; n_answered = 0
    n_within_2s = 0; n_within_4s = 0
    offsets = []
    for sid, qresults in out.items():
        for qid, r in qresults.items():
            if "done" not in r:
                continue
            n_total += 1
            if r.get("answered"):
                n_answered += 1
                off = r["abs_offset_sec"]
                offsets.append(off)
                if off <= 2.0: n_within_2s += 1
                if off <= 4.0: n_within_4s += 1
    return {
        "total_questions": n_total,
        "answered": n_answered,
        "answer_rate": (100 * n_answered / n_total) if n_total else 0,
        "acc_within_2s": (100 * n_within_2s / n_total) if n_total else 0,
        "acc_within_4s": (100 * n_within_4s / n_total) if n_total else 0,
        "mean_offset_sec": (sum(offsets) / len(offsets)) if offsets else 0,
    }


def _load_frame_captions(working_dir: str) -> List[dict]:
    """从 working_dir/frame_captions.json 读 caption 列表 (建图阶段保存)."""
    fp = os.path.join(working_dir, "frame_captions.json")
    if not os.path.isfile(fp):
        return []
    try:
        data = json.load(open(fp))
        return data.get("frame_captions", []) if isinstance(data, dict) else (data or [])
    except Exception:
        return []


def _maybe_init_hyper_vg(working_dir: str):
    """检索模式才需要实例化 HyperVideoGraph (走 BM25+语义双索引)."""
    from hypervideo.hyper_video_graph import HyperVideoGraph
    from hypervideo.config import HyperVideoConfig
    from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config2
    cfg = HyperVideoConfig(
        dataset_mode="forward",
        embedding_propagation_mode=os.environ.get("HYPERVIDEO_PROPAGATION_MODE", "residual"),
        embedding_propagation_lambda=float(os.environ.get("HYPERVIDEO_PROPAGATION_LAMBDA", "0.5")),
    )
    return HyperVideoGraph(working_dir=working_dir, llm=gpt5_2_llm_config2, hyper_config=cfg)


def main():
    # OPENAI key fallback: 不强制由调用方 export. 若未 set, 沿用 ovobench_hyper_retrieval main() 走过同样的 hardcoded key 路径
    # (生产环境推荐 export OPENAI_API_KEY=... 由调用方提供)
    if not os.environ.get("OPENAI_API_KEY"):
        # ovobench_hyper_retrieval 的 main() 在执行时硬编码这个 key, 这里 import 走 lazy 读源
        import re
        try:
            with open(__file__.replace("streamingbench_json_eval.py", "ovobench_hyper_retrieval.py")) as f:
                m = re.search(r'os\.environ\["OPENAI_API_KEY"\]\s*=\s*"(sk-[^"]+)"', f.read())
            if m:
                os.environ["OPENAI_API_KEY"] = m.group(1)
                logger.info("OPENAI_API_KEY 未 export, 已从 ovobench_hyper_retrieval 复用 hardcoded key")
        except Exception:
            pass
        if not os.environ.get("OPENAI_API_KEY"):
            raise RuntimeError("请先 export OPENAI_API_KEY=... 再运行本脚本")

    ap = argparse.ArgumentParser()
    ap.add_argument("--dataset", choices=["sqa", "contextual", "proactive"], required=True)
    ap.add_argument(
        "--mode", choices=["dump_all", "ep_retrieve", "agentic"], default="dump_all",
        help="MCQ 推理 mode (PO 不受影响). dump_all=全 fact 直答; "
             "ep_retrieve=只 episode + LLM 决策是否检索 (1次, fact_only); "
             "agentic=同上但鼓励有节制检索, 用 hierarchical 模式",
    )
    ap.add_argument(
        "--working_dir_root", type=str,
        default="/mnt/tokyo-ai/gst/GST_EGOSERVE/all_results",
    )
    ap.add_argument(
        "--datasets_type", type=str, required=True,
        help="working_dir 子目录, 例如 streamingbench_sqa_hyper",
    )
    ap.add_argument("--caption_model_name", type=str, default="qwen_api")
    ap.add_argument("--limit", type=int, default=0, help="只跑前 N samples (0=全部)")
    ap.add_argument("--output_path", type=str, required=True)
    ap.add_argument(
        '--answer_model', type=str, default='gpt-4.1-mini',
        help="LLM 推理模型. 候选: gpt-4.1-mini (default) / gpt-5.4-nano / gpt-5.4-mini",
    )
    ap.add_argument(
        '--propagation_mode', type=str, default='residual',
        choices=['residual', 'hypermem', 'none'],
        help="嵌入传播: residual (默认) / hypermem / none",
    )
    ap.add_argument(
        '--propagation_lambda', type=float, default=0.5,
    )
    args = ap.parse_args()

    # 应用 model + propagation 到 imported gpt5_2_llm_config + env
    os.environ["HYPERVIDEO_ANSWER_MODEL"] = args.answer_model
    os.environ["HYPERVIDEO_PROPAGATION_MODE"] = args.propagation_mode
    os.environ["HYPERVIDEO_PROPAGATION_LAMBDA"] = str(args.propagation_lambda)
    from hypervideo.ovobench_hyper_retrieval import gpt5_2_llm_config1, gpt5_2_llm_config2
    gpt5_2_llm_config1.best_model_name = args.answer_model
    gpt5_2_llm_config2.best_model_name = args.answer_model
    logger.info(f"[args] answer_model={args.answer_model} propagation_mode={args.propagation_mode} lambda={args.propagation_lambda}")

    is_sqa = args.dataset == "sqa"
    is_po = args.dataset == "proactive"
    needs_retrieval = (not is_po) and args.mode in ("ep_retrieve", "agentic")

    all_data = _load_dataset_for(args.dataset)
    if args.limit > 0:
        all_data = all_data[: args.limit]
    logger.info(
        f"加载 {len(all_data)} samples (dataset={args.dataset}, mode={args.mode})"
    )

    out: Dict[str, Dict[str, dict]] = {}
    if os.path.exists(args.output_path):
        try:
            out = json.load(open(args.output_path))
            logger.info(f"已加载历史结果 {sum(len(v) for v in out.values())} questions")
        except Exception:
            out = {}

    t_all = time.time()
    for sample_idx, item in enumerate(all_data):
        sid = item["id"]
        wd = os.path.join(
            args.working_dir_root, args.datasets_type, f"{sid}_{args.caption_model_name}"
        )
        hp = os.path.join(wd, "hypergraph.json")
        if not os.path.isfile(hp):
            logger.warning(f"[{sample_idx+1}/{len(all_data)}] {sid} 未建图, 跳过")
            continue
        try:
            hg = json.load(open(hp))
        except Exception as e:
            logger.warning(f"[{sample_idx+1}/{len(all_data)}] {sid} hypergraph 加载失败 {e}")
            continue
        all_frame_captions = _load_frame_captions(wd)

        # 检索模式才实例化 hyper_vg (开销较大)
        hyper_vg = None
        if needs_retrieval:
            try:
                hyper_vg = _maybe_init_hyper_vg(wd)
            except Exception as e:
                logger.warning(f"  hyper_vg 加载失败 ({e}), 该 sample 退化到 dump_all")

        prev = out.get(sid, {})
        if is_po:
            new_results = evaluate_po_sample(item, hg, prev,
                                              all_frame_captions=all_frame_captions)
        else:
            new_results = evaluate_mcq_sample(
                item, hg, is_sqa=is_sqa, prev_results=prev,
                mode=args.mode if hyper_vg is not None or args.mode == "dump_all" else "dump_all",
                all_frame_captions=all_frame_captions,
                hyper_vg=hyper_vg,
            )

        out[sid] = new_results

        # 进度日志
        if is_po:
            n_ans = sum(1 for r in new_results.values() if r.get("answered"))
            logger.info(
                f"[{sample_idx+1}/{len(all_data)}] {sid}: "
                f"{n_ans}/{len(new_results)} answered, "
                f"avg_offset={sum(r['abs_offset_sec'] for r in new_results.values() if r.get('answered'))/max(n_ans,1):.1f}s"
            )
        else:
            n_ok = sum(1 for r in new_results.values() if r.get("ok"))
            logger.info(
                f"[{sample_idx+1}/{len(all_data)}] {sid}: {n_ok}/{len(new_results)} correct"
            )

        # 持续保存
        if (sample_idx + 1) % 5 == 0:
            json.dump(out, open(args.output_path, "w"), ensure_ascii=False, indent=2)

    json.dump(out, open(args.output_path, "w"), ensure_ascii=False, indent=2)
    dt = time.time() - t_all
    logger.info(f"完成 {len(all_data)} samples, {dt:.0f}s")

    # 汇总
    if is_po:
        s = _score_po(out)
    else:
        s = _score_mcq(out)
    logger.info(f"=== {args.dataset} 汇总 ===")
    logger.info(json.dumps(s, indent=2, ensure_ascii=False))
    summary_path = args.output_path.replace(".json", "_summary.json")
    json.dump(s, open(summary_path, "w"), ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()