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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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
import { apiTyped } from '../lib/apiClient'
import { authHeaders } from '../lib/authHeader'
import { tracedFetch } from '../lib/api'

export type BatchJobsTotals = {
  batches: number
  running: number
  states: number
  states_planned: number
  states_started: number
  states_completed: number
  processed_jurisdictions: number
  failed_jurisdictions: number
  remaining_jurisdictions: number
  videos_ok: number
  videos_fail: number
  videos_attempted: number
  files_transcripts: number
  files_transcripts_disk: number
  transcript_hours: number
  bronze_download_rows: number
  files_analysis: number
  files_reports: number
  /** Analyses summarised in the last 24h (file mtime within the rolling window). */
  files_analysis_recent?: number
  /** Reports generated in the last 24h (file mtime within the rolling window). */
  files_reports_recent?: number
  /** Analysis errors stamped in the last 24h (bronze policy_analysis_error). */
  files_analysis_errors_recent?: number
  /** Report errors stamped in the last 24h (bronze policy_report_error). */
  files_reports_errors_recent?: number
  /** Most recent transcript-download stamp (all time, ISO) — "Last transcript" ago card. */
  last_transcript_at?: string
  /** Most recent analysis stamp (all time, ISO) — drives the "Last analysis" ago card. */
  last_analysis_at?: string
  /** Most recent report stamp (all time, ISO) — drives the "Last report" ago card. */
  last_report_at?: string
}

export type BatchVideoResult = {
  video_id: string
  title: string
  status: string
  error: string
  transcript_source: string
  finished_at: string
  duration_seconds?: number | null
}

export type BatchJurisdictionRun = {
  state_code: string
  jurisdiction_id: string
  jurisdiction_name: string
  status: string
  started_at: string
  updated_at?: string
  finished_at: string
  elapsed_seconds: number
  exit_code: number
  stats: Record<string, number>
  videos: BatchVideoResult[]
  file_counts: Record<string, number>
  current_video_id?: string
  current_video_title?: string
  current_video_started_at?: string
}

export type BatchJob = {
  batch_id: string
  step: string
  status: string
  started_at: string
  updated_at: string
  finished_at: string
  config: Record<string, unknown>
  summary: Record<string, unknown>
  jurisdictions: BatchJurisdictionRun[]
}

export type PipelineStage =
  | 'discover'
  | 'videos'
  | 'transcripts'
  | 'analyses_light'
  | 'reports_light'
  | 'analyses_full'
  | 'reports_full'
  // Legacy aliases (pre-#755) — still accepted if an older API payload arrives.
  | 'analyses'
  | 'reports'

export const FULL_FILTER_OPTIONS = [
  { key: 'has_decisions', label: 'Has decisions', defaultChecked: true },
  { key: 'interestingness', label: 'High interestingness', defaultChecked: true },
  { key: 'data_center', label: 'Data-center mention', defaultChecked: false },
] as const

export type FullFilterKey = (typeof FULL_FILTER_OPTIONS)[number]['key']

/** Per-entity split of a stage (discover: counties vs municipalities). Sums to the row. */
export type StageBreakdownEntry = {
  entity: string
  done: number
  total: number
  failed: number
}

/** One (scope, stage) row. ``scope`` is a 2-letter state code or ``ALL`` (rollup). */
export type StageReportRow = {
  scope: string
  stage: PipelineStage | string
  done: number
  total: number
  failed: number
  last_at: string
  /** Optional per-entity split (only the discover stage today). */
  breakdown?: StageBreakdownEntry[]
}

export type StageTiming = {
  avg_seconds?: number | null
  last_path?: string
  last_at?: string
}

export type StageReport = {
  states: string[]
  rows: StageReportRow[]
  /** Per-stage cadence + last file: keyed by stage name. */
  timing?: Record<string, StageTiming>
}

export type LaunchLog = {
  step: string
  path: string
  lines: string[]
  /** Best-effort "current item" line parsed from the log tail. */
  current: string
  current_since: string
  /** Operator blocker from the log tail (billing / VPN) (#699). */
  blocker?: string | null
}

export async function fetchLaunchLog(step: string): Promise<LaunchLog> {
  const r = await tracedFetch(
    `/api/batch-jobs/launch/log?step=${encodeURIComponent(step)}&lines=150`,
    { headers: authHeaders(), signal: AbortSignal.timeout(10_000) },
  )
  if (!r.ok) throw new Error(`HTTP ${r.status}`)
  return (await r.json()) as LaunchLog
}

export type BatchJobsDashboardPayload = {
  generated_at: string
  /** Latest batch/jurisdiction progress timestamp (not API build time). */
  last_activity_at?: string
  totals: BatchJobsTotals
  batches: BatchJob[]
  /** Long-format per-state pipeline coverage (scope×stage rows). */
  stage_report?: StageReport
  source?: 'database' | 'files'
  /** ``summary`` = metrics only; ``full`` = all per-video rows included. */
  detail?: 'summary' | 'full' | string
}

export type LaunchStatus = {
  enabled: boolean
  busy: boolean
  running: number
  /** Steps currently running — different steps can run concurrently. */
  running_steps: string[]
  /** Live but stalled (>1h no activity) — re-launchable. */
  stalled_steps: string[]
  steps: string[]
  /** Operator warning when a live launch is inactive, VPN down, or billing exhausted. */
  warning?: string
  /** True when the newest launch log mentions Surfshark / VPN required. */
  vpn_down?: boolean
  /** True when launch log shows Gemini 402 prepaid credits depleted (#699). */
  billing_exhausted?: boolean
  /** Seconds since the most inactive live launch last progressed (log/DB). */
  inactive_seconds?: number | null
  /** Steps the watchdog re-spawned on this poll (#752). */
  resumed_steps?: string[]
  /** Human note for auto-resume / waiting-for-VPN (#752). */
  auto_resume_note?: string
}

export type LaunchResult = {
  launched: boolean
  pid?: number | null
  step: string
  states: string[]
  log: string
  detail: string
}

export async function fetchLaunchStatus(): Promise<LaunchStatus> {
  const r = await tracedFetch('/api/batch-jobs/launch', {
    signal: AbortSignal.timeout(10_000),
  })
  if (!r.ok) throw new Error(`HTTP ${r.status}`)
  return (await r.json()) as LaunchStatus
}

export async function launchPipeline(body: {
  step: string
  states?: string[]
  n?: number
  parallel?: number
  cohort?: BatchCohort
  full_filters?: string[]
}): Promise<LaunchResult> {
  const r = await tracedFetch('/api/batch-jobs/launch', {
    method: 'POST',
    headers: authHeaders({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(15_000),
  })
  if (!r.ok) {
    let detail = `HTTP ${r.status}`
    try {
      const j = (await r.json()) as { error?: string; detail?: string }
      if (j?.error || j?.detail) detail = (j.error || j.detail) as string
    } catch {
      /* ignore */
    }
    throw new Error(detail)
  }
  return (await r.json()) as LaunchResult
}

export type StopResult = {
  stopped: number
  steps: string[]
  pids: number[]
  detail: string
}

/** Stop running pipeline launch(es). Omit `step` to stop everything. */
export async function stopPipeline(body: {
  step?: string
  force?: boolean
} = {}): Promise<StopResult> {
  const r = await tracedFetch('/api/batch-jobs/launch/stop', {
    method: 'POST',
    headers: authHeaders({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(15_000),
  })
  if (!r.ok) {
    let detail = `HTTP ${r.status}`
    try {
      const j = (await r.json()) as { error?: string; detail?: string }
      if (j?.error || j?.detail) detail = (j.error || j.detail) as string
    } catch {
      /* ignore */
    }
    throw new Error(detail)
  }
  return (await r.json()) as StopResult
}

export type BatchCohort = 'priority' | 'data_centers' | 'all'

export type CohortsResponse = {
  priority: string[]
  data_centers: string[]
  all: string[]
}

export async function fetchCohorts(): Promise<CohortsResponse> {
  const r = await tracedFetch('/api/batch-jobs/cohorts', {
    headers: authHeaders(),
    signal: AbortSignal.timeout(15_000),
  })
  if (!r.ok) throw new Error(`HTTP ${r.status}`)
  return (await r.json()) as CohortsResponse
}

export type BatchJobsDetailLevel = 'summary' | 'standard' | 'full'

type ApiErrorBody = { detail?: string | { msg?: string }[] }

/** User-visible message from failed ``api.get`` (includes FastAPI ``detail``). */
export function batchJobsFetchErrorMessage(error: unknown): string {
  const err = error as {
    message?: string
    response?: { data?: ApiErrorBody; status?: number; statusText?: string }
  }
  const detail = err.response?.data?.detail
  if (typeof detail === 'string' && detail.trim()) {
    return detail
  }
  if (Array.isArray(detail)) {
    const text = detail.map((d) => d?.msg).filter(Boolean).join('; ')
    if (text) return text
  }
  if (err.response?.status) {
    return `HTTP ${err.response.status}: ${err.response.statusText ?? 'Error'}`
  }
  return err.message ?? 'unknown error'
}

export async function fetchBatchJobsDashboard(
  refreshFiles = false,
  detail: BatchJobsDetailLevel = 'summary',
  cohort?: BatchCohort,
): Promise<BatchJobsDashboardPayload> {
  const query = new URLSearchParams({
    refresh_files: String(refreshFiles),
    enrich_bronze: 'false',
    detail,
    batch_limit: '25',
  })
  if (cohort) query.set('cohort', cohort)
  const r = await tracedFetch(`/api/batch-jobs/?${query}`, {
    headers: authHeaders(),
    signal: AbortSignal.timeout(30_000),
  })
  if (!r.ok) {
    let detailMsg = `HTTP ${r.status}`
    try {
      const j = (await r.json()) as { detail?: string }
      if (j?.detail) detailMsg = j.detail
    } catch {
      /* ignore */
    }
    throw new Error(detailMsg)
  }
  const data = (await r.json()) as BatchJobsDashboardPayload
  if (data == null) {
    // openapi-fetch resolved with neither data nor error — e.g. an empty body
    // or a 30s-aborted request. Returning undefined here makes React Query emit
    // a cryptic "data is undefined" error; throw a real message instead.
    throw new Error(
      'Batch jobs API returned an empty response (the API may be down, restarting, or slow — try restarting it and reloading).',
    )
  }
  return data
}

// ---- Why did videos fail? (#792) -------------------------------------------------

export type FailureStage = 'videos' | 'transcripts'

export type FailureReasonGroup = {
  key: string
  label: string
  advice: string
  /** True when trying again can work; false for no captions, private or removed videos. */
  retryable: boolean
  count: number
  reasons: Array<{
    reason: string
    /** Short id for this reason (md5 of the normalized text); the videos request uses it. */
    reason_id: string
    count: number
    example: string
    /** A video that failed with this reason, for a link to watch it. */
    example_video_id: string | null
  }>
}

export type FailureReasonsPayload = {
  stage: string
  cohort: string
  state: string
  total: number
  truncated: boolean
  groups: FailureReasonGroup[]
}

export type FailureRowsPayload = {
  stage: string
  reason_id: string
  total: number
  rows: Array<{
    video_id: string
    title: string
    jurisdiction_id: string
    jurisdiction_name: string
    state_code: string
    error: string
  }>
}

async function getJson<T>(path: string, query: URLSearchParams): Promise<T> {
  const r = await tracedFetch(`${path}?${query}`, {
    headers: authHeaders(),
    signal: AbortSignal.timeout(60_000),
  })
  if (!r.ok) {
    let detailMsg = `HTTP ${r.status}`
    try {
      const j = (await r.json()) as { detail?: string }
      if (j?.detail) detailMsg = j.detail
    } catch {
      /* ignore */
    }
    throw new Error(detailMsg)
  }
  return (await r.json()) as T
}

export function fetchFailureReasons(
  stage: FailureStage,
  cohort: string,
  state: string,
): Promise<FailureReasonsPayload> {
  const q = new URLSearchParams({ stage, cohort })
  if (state) q.set('state', state)
  return getJson<FailureReasonsPayload>('/api/batch-jobs/failure-reasons', q)
}

export function fetchFailureRows(
  stage: FailureStage,
  cohort: string,
  state: string,
  reasonId: string,
  offset: number,
  limit = 50,
): Promise<FailureRowsPayload> {
  const q = new URLSearchParams({
    stage,
    cohort,
    reason_id: reasonId,
    offset: String(offset),
    limit: String(limit),
  })
  if (state) q.set('state', state)
  return getJson<FailureRowsPayload>('/api/batch-jobs/failures', q)
}

export type RetryFailuresResult = {
  stage: string
  group: string
  reason_id: string
  dry_run: boolean
  /** Failed videos in the chosen group or reason. */
  matched: number
  /** Videos that were waiting out the 30-day cooldown and are now due. */
  made_due: number
  /** Videos with no cooldown: the next Backfill already picks them up. */
  already_due: number
}

/** Make the failed videos of a retryable group (or one reason) due for the next caption Backfill.
 *  Deletes nothing. ``dry_run`` only counts. */
export async function retryFailures(body: {
  stage: FailureStage
  cohort: string
  state: string
  group?: string
  reason_id?: string
  dry_run: boolean
}): Promise<RetryFailuresResult> {
  const r = await tracedFetch('/api/batch-jobs/failures/retry', {
    method: 'POST',
    headers: authHeaders({ 'Content-Type': 'application/json' }),
    body: JSON.stringify({ ...body, state: body.state || null }),
    signal: AbortSignal.timeout(60_000),
  })
  if (!r.ok) {
    let detailMsg = `HTTP ${r.status}`
    try {
      const j = (await r.json()) as { detail?: string }
      if (j?.detail) detailMsg = j.detail
    } catch {
      /* ignore */
    }
    throw new Error(detailMsg)
  }
  return (await r.json()) as RetryFailuresResult
}

export type FailedVideosListPayload = {
  rows: Array<{
    batch_id: string
    batch_step: string
    state_code: string
    jurisdiction_id: string
    jurisdiction_name: string
    video: BatchVideoResult
  }>
  total_fail_in_summaries: number
  truncated: boolean
}

export async function fetchFailedVideos(
  batchId?: string,
  limit = 500,
): Promise<FailedVideosListPayload> {
  const { data, error } = await apiTyped.GET('/api/batch-jobs/failed-videos', {
    params: {
      query: { ...(batchId ? { batch_id: batchId } : {}), limit },
    },
    signal: AbortSignal.timeout(60_000),
  })
  if (error) throw error
  return data as FailedVideosListPayload
}

export async function fetchBatchJurisdictions(
  batchId: string,
  stateCode: string,
): Promise<BatchJurisdictionRun[]> {
  const { data, error } = await apiTyped.GET(
    '/api/batch-jobs/{batch_id}/jurisdictions',
    { params: { path: { batch_id: batchId }, query: { state: stateCode.toUpperCase() } } },
  )
  if (error) throw error
  return (data.jurisdictions ?? []) as BatchJurisdictionRun[]
}

export async function fetchBatchJobDetail(
  batchId: string,
  includeVideos: 'all' | 'failed_only' | 'none' | 'running' = 'all',
): Promise<BatchJob> {
  const { data, error } = await apiTyped.GET('/api/batch-jobs/{batch_id}', {
    params: {
      path: { batch_id: batchId },
      query: { enrich_bronze: false, include_videos: includeVideos },
    },
  })
  if (error) throw error
  return data as BatchJob
}

/** Attach on-demand jurisdiction rows to a summary-only batch row. */
export function mergeBatchJurisdictions(
  batch: BatchJob,
  jurisdictions: BatchJurisdictionRun[],
): BatchJob {
  return { ...batch, jurisdictions }
}

/** Merge jurisdiction rows (and videos) from a detail fetch into cached dashboard data. */
export function mergeBatchIntoDashboard(
  prev: BatchJobsDashboardPayload | undefined,
  batch: BatchJob,
): BatchJobsDashboardPayload | undefined {
  if (!prev) return prev
  const batches = prev.batches.map((b) =>
    b.batch_id === batch.batch_id ? { ...b, ...batch, jurisdictions: batch.jurisdictions } : b,
  )
  if (!batches.some((b) => b.batch_id === batch.batch_id)) {
    batches.unshift(batch)
  }
  return { ...prev, batches, detail: 'full' }
}

/** SSE URL for live dashboard updates (Postgres-backed). */
export function batchJobsStreamUrl(cohort?: BatchCohort): string {
  const base = import.meta.env.PROD
    ? '/api'
    : import.meta.env.VITE_API_URL || '/api'
  const prefix = base.endsWith('/') ? base.slice(0, -1) : base
  const q = cohort ? `?cohort=${encodeURIComponent(cohort)}` : ''
  return `${prefix}/batch-jobs/stream${q}`
}

// #800: the grid of failed items for every stage.
export type FailureGridStage =
  | 'videos'
  | 'transcripts'
  | 'analyses_light'
  | 'reports_light'
  | 'analyses_full'
  | 'reports_full'

export type FailureGridRow = {
  video_id: string
  title: string
  jurisdiction_id: string
  jurisdiction_name: string
  state_code: string
  channel_id: string
  channel_url: string
  event_date: string
  meeting_type: string
  error: string
  group: string
  group_label: string
  advice: string
  retryable: boolean
  last_updated: string
  event_id: string
}

export type FailureGridPayload = {
  stage: string
  cohort: string
  state: string
  error_column: string
  where_to_look: string
  total: number
  columns: { key: string; label: string; sortable: boolean }[]
  rows: FailureGridRow[]
}

export function fetchFailureGrid(opts: {
  stage: FailureGridStage
  cohort: string
  state: string
  q: string
  group: string
  sort: string
  dir: 'asc' | 'desc'
  limit: number
  offset: number
}): Promise<FailureGridPayload> {
  const q = new URLSearchParams({
    stage: opts.stage,
    cohort: opts.cohort,
    sort: opts.sort,
    dir: opts.dir,
    limit: String(opts.limit),
    offset: String(opts.offset),
  })
  if (opts.state) q.set('state', opts.state)
  if (opts.q) q.set('q', opts.q)
  if (opts.group) q.set('group', opts.group)
  return getJson<FailureGridPayload>('/api/batch-jobs/failure-grid', q)
}