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28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
"""
agent0_sectioner.py
-------------------
Agent 0: The Structural Segmenter.

Identifies topical sections / activity phases in a Zoom transcript BEFORE
any behavioral coding takes place. This mirrors how experienced qualitative
coders orient to data: macro-structure first, micro-coding second.

Theoretical basis
-----------------
Human annotation practice β€” unitising precedes categorising:
  Krippendorff, K. (2004). Content analysis: An introduction to its
    methodology (2nd ed., ch. 7). Sage.

Topic/phase segmentation in spoken discourse:
  Hearst, M. A. (1997). TextTiling: Segmenting text into multi-paragraph
    subtopic passages. Computational Linguistics, 23(1), 33–64.

  Purver, M., KΓΆrding, K., Griffiths, T., & Tenenbaum, J. (2006).
    Unsupervised topic modelling for multi-party spoken discourse.
    Proceedings of COLING-ACL, 17–24.

  Galley, M., McKeown, K., Hirschberg, J., & Shriberg, E. (2003).
    Identifying agreement and disagreement in conversational speech.
    Proceedings of ACL.

Activity phases in collaborative work:
  Stahl, G. (2006). Group cognition: Computer support for building
    collaborative knowledge. MIT Press.

  Roschelle, J., & Teasley, S. D. (1995). The construction of shared
    knowledge in collaborative problem solving. In C. O'Malley (Ed.),
    Computer-supported collaborative learning. Springer.

Cognitive load / working memory rationale for section size:
  Sweller, J. (1988). Cognitive load during problem solving: Effects on
    learning. Cognitive Science, 12(2), 257–285.
    β€” Analysts hold 15–50 turns comfortably before cognitive overload
      degrades annotation reliability.

Design rationale
----------------
Agent 0 runs ONCE per transcript as the first automated step. The researcher
MUST confirm (or edit) sections before Agent 1a processes any section.
This human checkpoint prevents the "hour-long transcript overload" problem
by decomposing the session into reviewable units that match natural
conversational structure β€” not arbitrary character counts.

Agent 0 does NOT assign dimension codes. It only identifies where coherent
activity phases begin and end.
"""

from __future__ import annotations

import json
import os
import re
from collections import Counter
from pathlib import Path
from typing import Optional

from llm_client import call_llm

LIBRARY_ROOT = Path(__file__).parent / "library"
TIER1_PATH   = LIBRARY_ROOT / "tier1_core"

MAX_TOKENS = 2000

# Target section size β€” mirrors human working memory limits for discourse
# analysis. Analysts reliably process 15-50 turns per coding pass.
# (Sweller 1988; Krippendorff 2004 ch.7)
TARGET_TURNS_PER_SECTION = 30
MIN_TURNS_PER_SECTION    = 10


# ---------------------------------------------------------------------------
# Library loader
# ---------------------------------------------------------------------------

def load_dimension_labels() -> list[dict]:
    """Load dimension IDs and labels as naming hints for sections."""
    dims = json.loads((TIER1_PATH / "dimensions.json").read_text())
    return [{"id": d["id"], "label": d["label"]} for d in dims["dimensions"]]


# ---------------------------------------------------------------------------
# Formatters
# ---------------------------------------------------------------------------

_MEDIUM_THRESHOLD = 200   # turns; 60-char truncation above this
_LARGE_THRESHOLD  = 400   # turns; 40-char truncation + sampling above this
_XLARGE_THRESHOLD = 600   # turns; 30-char truncation + 2Γ— sampling above this

def _format_turns_compact(turns: list[dict]) -> str:
    """
    Adaptive prompt compression for Agent 0.

    Agent 0 only needs topic-shift signals to place section boundaries β€”
    it does NOT need full turn text. Aggressive truncation cuts token count
    while preserving boundary-relevant information (speaker identity,
    time, first few words of each turn).

    Tier    | Threshold | Max chars | Sampling   | Est. tokens
    --------|-----------|-----------|------------|-------------
    Short   | ≀ 200     | 120       | every turn | ~5,000
    Medium  | ≀ 400     | 60        | every turn | ~6,000
    Large   | ≀ 600     | 40        | every turn | ~8,000
    X-Large | > 600     | 30        | every 2nd  | ~5,500

    For x-large transcripts, we sample every 2nd turn. Adjacent turns
    from the same speaker are structurally redundant for section detection;
    skipping them preserves all speaker-change signals while halving tokens.
    A sentinel line marks each skipped block so the LLM knows turns exist.
    """
    n = len(turns)
    if n > _XLARGE_THRESHOLD:
        maxlen, step = 30, 2
    elif n > _LARGE_THRESHOLD:
        maxlen, step = 40, 1
    elif n > _MEDIUM_THRESHOLD:
        maxlen, step = 60, 1
    else:
        maxlen, step = 120, 1

    lines = []
    i = 0
    while i < len(turns):
        t    = turns[i]
        text = t["text"][:maxlen] + "…" if len(t["text"]) > maxlen else t["text"]
        lines.append(f"[{t['turn_id']:>4}] {t['start_time']}  {t['speaker']}: {text}")
        if step == 2 and i + 1 < len(turns):
            skipped = turns[i + 1]
            lines.append(
                f"[{skipped['turn_id']:>4}] {skipped['start_time']}  "
                f"{skipped['speaker']}: (…)"
            )
        i += step

    if step > 1:
        lines.append(
            f"\n[NOTE: {n} turns total; every other turn shown for brevity. "
            f"Turn IDs are sequential β€” all turns exist between shown IDs.]"
        )

    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Prompt builder
# ---------------------------------------------------------------------------

def build_system_prompt(dimension_labels: list[dict]) -> str:
    dim_hint = ", ".join(f"{d['id']} ({d['label']})" for d in dimension_labels)
    return f"""You are a discourse analyst specialising in computer-supported collaborative learning.
Your task is to segment a Zoom transcript into coherent topical sections β€”
natural activity phases where the dyad is engaged in a common focus.

This is STRUCTURAL segmentation, NOT behavioral coding.
You are identifying where one activity phase ends and another begins.

Boundary signals to look for (Hearst 1997; Purver et al. 2006):
  - Explicit transition markers: "OK let's move on", "now we need to", "right so..."
  - Changes in the primary task (planning β†’ implementation, coding β†’ testing)
  - Shifts in who is driving vs. supporting
  - Topic exhaustion followed by a new initiation
  - Breaks and re-orientation turns

Each section must:
  - Be large enough to contain multiple behavioral episodes (β‰₯ {MIN_TURNS_PER_SECTION} turns)
  - Have a descriptive activity label (e.g. "Task Orientation", "Collaborative Coding",
    "Debugging Session", "Review and Reflection", "Planning Next Steps")
  - Have a 1–2 sentence summary of what the dyad is doing in that phase

Dimension framework hint (for label context only β€” do not assign codes):
{dim_hint}

Output ONLY valid JSON β€” no preamble, no explanation outside the JSON:
{{
  "sections": [
    {{
      "section_id": "s01",
      "label": "activity label",
      "summary": "1–2 sentence description of the dyad's activity in this phase",
      "start_turn_id": 0,
      "end_turn_id": 45,
      "start_time": "HH:MM:SS",
      "end_time": "HH:MM:SS"
    }}
  ],
  "session_overview": "2–3 sentence summary of the full session arc"
}}

The sections must be contiguous and cover every turn in the transcript.
Aim for 3–8 sections of roughly equal size.
"""


def build_user_prompt(turns: list[dict]) -> str:
    return f"""Please segment the following transcript into topical sections.
{len(turns)} turns total (turn IDs {turns[0]['turn_id']} – {turns[-1]['turn_id']}).

=== TRANSCRIPT ===
{_format_turns_compact(turns)}

Identify 3–8 sections that reflect the natural activity phases of this session.
"""


# ---------------------------------------------------------------------------
# Response parser and validator
# ---------------------------------------------------------------------------

def _parse_response(raw: str) -> dict:
    cleaned = raw.strip()
    if cleaned.startswith("```"):
        cleaned = "\n".join(cleaned.split("\n")[1:])
    if cleaned.endswith("```"):
        cleaned = "\n".join(cleaned.split("\n")[:-1])
    cleaned = cleaned.strip()
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError as e:
        raise ValueError(
            f"Agent 0 returned invalid JSON.\nError: {e}\nRaw:\n{raw}"
        ) from e


def _validate_sections(sections: list[dict], turns: list[dict]) -> list[str]:
    """Check sections are contiguous and cover all turns."""
    errors = []
    if not sections:
        errors.append("No sections returned.")
        return errors

    all_turn_ids = {t["turn_id"] for t in turns}
    covered: set[int] = set()

    for s in sections:
        start = s.get("start_turn_id")
        end   = s.get("end_turn_id")
        if start is None or end is None:
            errors.append(f"Section {s.get('section_id')} missing turn range.")
            continue
        section_range = set(range(start, end + 1))
        overlap = covered & section_range
        if overlap:
            errors.append(
                f"Section {s.get('section_id')} overlaps prior sections "
                f"at turns {sorted(overlap)[:5]}"
            )
        covered.update(section_range)

    missing = all_turn_ids - covered
    if missing:
        errors.append(
            f"{len(missing)} turns not covered by any section: "
            f"{sorted(missing)[:10]}"
        )

    return errors


# ---------------------------------------------------------------------------
# Heuristic fallback
# ---------------------------------------------------------------------------

_BOUNDARY_PATTERNS = [
    re.compile(r"\b(ok|okay|right|so|well)\b.*\b(move on|next|now|let's)\b", re.I),
    re.compile(r"\b(now|next|then|after that|at the same time)\b", re.I),
    re.compile(r"\b(let's|we should|we need to|we have to)\b", re.I),
    re.compile(r"\b(debug|fix|test|check|review|plan|summary|wrap up|finish)\b", re.I),
]


def _turn_text(turn: dict) -> str:
    return f"{turn.get('speaker', '')} {turn.get('text', '')}".strip()


def _boundary_score(turn: dict) -> int:
    text = _turn_text(turn)
    score = 0
    for pat in _BOUNDARY_PATTERNS:
        if pat.search(text):
            score += 1
    if len(text) < 20:
        score += 1
    return score


def _heuristic_sections(turns: list[dict]) -> dict:
    """Simple local segmentation when the remote LLM is unavailable."""
    n = len(turns)
    if n == 0:
        return {"sections": [], "session_overview": ""}

    target = TARGET_TURNS_PER_SECTION
    min_size = MIN_TURNS_PER_SECTION
    sections = []
    start_idx = 0
    section_num = 1

    while start_idx < n:
        remaining = n - start_idx
        if remaining <= target + 5:
            end_idx = n - 1
        else:
            candidate = min(start_idx + target - 1, n - 1)
            window_start = max(start_idx + min_size - 1, candidate - 5)
            window_end = min(n - min_size, candidate + 5)
            best_idx = candidate
            best_score = -1
            for idx in range(window_start, window_end + 1):
                score = _boundary_score(turns[idx])
                if score > best_score:
                    best_score = score
                    best_idx = idx
            end_idx = best_idx

        seg_turns = turns[start_idx : end_idx + 1]
        label = f"Phase {section_num}"
        texts = " ".join(t.get("text", "") for t in seg_turns).lower()
        if any(k in texts for k in ["plan", "planning", "organize", "setup"]):
            label = f"Planning Phase {section_num}"
        elif any(k in texts for k in ["debug", "fix", "error", "bug", "issue"]):
            label = f"Debugging Phase {section_num}"
        elif any(k in texts for k in ["test", "testing", "try", "check"]):
            label = f"Testing Phase {section_num}"
        elif any(k in texts for k in ["review", "reflect", "summary", "wrap up"]):
            label = f"Review Phase {section_num}"

        sections.append(
            {
                "section_id": f"s{section_num:02d}",
                "label": label,
                "summary": (
                    f"Heuristic local segment covering {len(seg_turns)} turns. "
                    f"Use this as a draft when remote sectioning is unavailable."
                ),
                "start_turn_id": seg_turns[0]["turn_id"],
                "end_turn_id": seg_turns[-1]["turn_id"],
                "start_time": seg_turns[0].get("start_time", ""),
                "end_time": seg_turns[-1].get("end_time", ""),
            }
        )
        start_idx = end_idx + 1
        section_num += 1

    overview = f"Local heuristic segmentation created {len(sections)} sections because the remote LLM was unavailable."
    return {"sections": sections, "session_overview": overview}


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def run_sectioning(
    turns: list[dict],
    session_id: str,
    library_root: Optional[Path] = None,
) -> dict:
    """
    Segment a full transcript into topical sections.

    Args:
        turns:        Full list of parsed turn dicts.
        session_id:   Identifier for this session.
        library_root: Override library path (for testing).

    Returns:
        Dict with: sections (list), session_overview (str), session_id, warnings (list).
    """
    global LIBRARY_ROOT, TIER1_PATH
    if library_root:
        LIBRARY_ROOT = library_root
        TIER1_PATH   = library_root / "tier1_core"

    if not turns:
        raise ValueError("No turns provided.")

    print(f"[Agent 0] Segmenting {len(turns)} turns into topical sections...")

    dimension_labels = load_dimension_labels()
    system_prompt    = build_system_prompt(dimension_labels)
    user_prompt      = build_user_prompt(turns)

    fallback_requested = os.environ.get("LOCAL_SECTIONING", "").strip().lower() in {"1", "true", "yes", "on"}

    if fallback_requested:
        print("[Agent 0] LOCAL_SECTIONING enabled β€” using heuristic fallback.")
        result = _heuristic_sections(turns)
    else:
        try:
            raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
            result = _parse_response(raw)
        except Exception as exc:
            msg = str(exc).lower()
            billing_error = any(token in msg for token in ["prepaid", "credit", "billing", "payment", "quota", "insufficient"])
            if billing_error:
                print("[Agent 0] Remote LLM billing issue detected β€” using heuristic fallback.")
                result = _heuristic_sections(turns)
            else:
                raise

    sections = result.get("sections", [])
    overview = result.get("session_overview", "")
    warnings = _validate_sections(sections, turns)

    if warnings:
        print(f"[Agent 0] Validation warnings: {warnings}")

    print(f"[Agent 0] Proposed {len(sections)} sections:")
    for s in sections:
        n = s["end_turn_id"] - s["start_turn_id"] + 1
        print(f"  {s['section_id']}: {s['label']} "
              f"({n} turns, {s['start_time']}–{s['end_time']})")

    return {
        "session_id":       session_id,
        "sections":         sections,
        "session_overview": overview,
        "warnings":         warnings,
    }


def save_sections(result: dict, output_path: Path) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(
        json.dumps(result, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    print(f"[Agent 0] Sections saved to {output_path}")