File size: 30,770 Bytes
b688fe8
 
dcedba8
 
b688fe8
 
 
 
 
 
 
 
 
 
9fde2ee
8a3fe26
a2ea1c4
02083ad
8a3fe26
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167eaae
 
b688fe8
 
53bbeda
b688fe8
 
 
 
 
bdadcbf
 
b688fe8
 
 
 
 
90aef7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
90aef7e
 
b688fe8
 
 
90aef7e
b688fe8
 
 
90aef7e
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
 
bdadcbf
b688fe8
 
 
 
 
bdadcbf
 
 
 
 
b688fe8
 
 
 
bdadcbf
b688fe8
 
 
 
 
 
0671a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
 
 
8a3fe26
 
cc1f86e
 
 
 
167eaae
c74d87a
167eaae
cc1f86e
 
8a3fe26
 
a2ea1c4
02083ad
 
 
 
 
ca54280
02083ad
 
 
 
 
dcedba8
 
 
18851c3
 
 
 
167eaae
c74d87a
 
 
 
03173b6
c74d87a
8a3fe26
 
 
b688fe8
 
 
0671a8c
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
968115e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53bbeda
b688fe8
 
 
 
 
5895e58
 
 
 
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fde2ee
 
 
 
 
b688fe8
 
 
40ae261
 
 
 
37dd634
40ae261
b688fe8
 
 
 
 
 
 
82daa40
 
 
 
 
 
40ae261
 
 
 
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
768d5c8
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53bbeda
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5895e58
b688fe8
 
 
5895e58
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a3fe26
 
 
 
 
 
 
 
 
 
cc1f86e
167eaae
968115e
167eaae
c74d87a
 
 
8a3fe26
 
 
 
 
 
 
 
 
cc1f86e
167eaae
968115e
167eaae
c74d87a
 
 
8a3fe26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2ea1c4
 
 
 
 
 
 
 
 
 
02083ad
 
 
ca54280
 
 
968115e
 
 
a2ea1c4
 
 
 
 
 
 
 
02083ad
 
ca54280
 
 
02083ad
968115e
 
 
a2ea1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
 
53bbeda
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
968115e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e2b849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
968115e
 
 
2e2b849
 
 
 
 
 
b688fe8
dcedba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b688fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
968115e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import { supabase } from "./supabase";
import type {
  BookCatalog,
  BookDesignResult,
  AdminAnnouncement,
  AdminUserRow,
  Reconciliation,
  TaskTypeSpend,
  UsageMatrix,
  UserDetail,
  AdminOverview,
  AdminRunDetail,
  AnnouncementItem,
  AuditEntry,
  CatalogueEntry,
  DesignResult,
  SlideDesignResult,
  SlideImages,
  DesignableRun,
  DesignTemplate,
  JsonSchema,
  LibraryItem,
  ProfileInput,
  SavedProfile,
  TaskType,
  UsageSummary,
  AdminRun,
  ArtifactMeta,
  UploadMeta,
  ModelBreakdown,
  PipelineBreakdown,
  PipelineDef,
  Profile,
  Project,
  ReviewPayload,
  Run,
  RunDetail,
  SeriesPoint,
  UserUsage,
  SavedImages,
  ImageModelTier,
} from "./types";

export const API_URL = import.meta.env.VITE_API_URL ?? "http://127.0.0.1:8000";

export class ApiError extends Error {
  constructor(
    readonly status: number,
    message: string,
    /* a form's refusal field by field: `{field, detail}` (routes._check_brief) */
    readonly errors: { field?: string; detail?: string }[] = [],
  ) {
    super(message);
  }
}

/* ยซtoken expiredยป while editing a chapter of a novel's plan (2026-11-16):
   a tab left in the background stops the session's refresh timer, and the
   hour-long token ran out under the page. The token is renewed before a
   request when it has under two minutes left, and once more when the server
   still says it expired - the request is then sent again, and the person
   never sees it. */
const RENEW_MS = 120_000;

async function authHeader(force = false): Promise<Record<string, string>> {
  let { data } = await supabase.auth.getSession();
  const ends = (data.session?.expires_at ?? 0) * 1000;
  if (data.session && (force || ends - Date.now() < RENEW_MS)) {
    const renewed = await supabase.auth.refreshSession();
    if (renewed.data.session) data = { session: renewed.data.session };
  }
  const token = data.session?.access_token;
  return token ? { Authorization: `Bearer ${token}` } : {};
}

async function send(path: string, init: RequestInit, force = false): Promise<Response> {
  return fetch(`${API_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      ...(await authHeader(force)),
      ...(init.headers ?? {}),
    },
  });
}

async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
  let res = await send(path, init);
  if (res.status === 401) {
    // the session ran out under the page: renewed, and the request sent again
    const said = await res.clone().text().catch(() => "");
    if (/expired|missing Authorization/i.test(said)) {
      res = await send(path, init, true);
      if (res.status === 401) {
        throw new ApiError(401, "ุงู†ุชู‡ุช ุฌู„ุณุชูƒ - ุณุฌู‘ู„ ุงู„ุฏุฎูˆู„ ู…ู† ุฌุฏูŠุฏ. ู…ุง ูƒุชุจุชู‡ ููŠ ุงู„ุตูุญุฉ ุจุงู‚ู ููŠู‡ุง.");
      }
    }
  }

  if (!res.ok) {
    // FastAPI puts the human-readable reason in `detail`; surface that rather
    // than a bare status code, because these strings are written to be shown.
    let message = `ุงู„ุทู„ุจ ูุดู„ (${res.status})`;
    let errors: { field?: string; detail?: string }[] = [];
    try {
      const body = await res.json();
      if (typeof body?.detail === "string") message = body.detail;
      else if (Array.isArray(body?.detail)) {
        message = body.detail.map((d: { msg: string }) => d.msg).join("ุŒ ");
      } else if (body?.detail && typeof body.detail === "object") {
        // ยซุงู„ุทู„ุจ ูุดู„ (422)ยป hid which field the server named (2026-11-15)
        errors = Array.isArray(body.detail.errors) ? body.detail.errors : [];
        const named = errors.map((e) => `${e.field ?? ""}: ${e.detail ?? ""}`).join("ุŒ ");
        message = [body.detail.message, named].filter(Boolean).join(" โ€” ") || message;
      }
    } catch {
      /* keep the fallback */
    }
    throw new ApiError(res.status, message, errors);
  }

  if (res.status === 204) return undefined as T;
  return res.json() as Promise<T>;
}

/* ยซู‚ุฑุฃู†ุง ุชุตูˆุฑูƒ ูƒุฏู‡ยป: a supplied design read before the run (api/v1/blueprint_read). */
export type BlueprintReading = {
  reading: Record<string, unknown>;
  reading_digest: string;
  notes: string[];
  summary: {
    kind: "book" | "bag";
    chapters: number;
    items: number;
    days?: number;
    rows: { title: string; children: string[]; points: number }[];
  };
};

export const api = {
  // profile
  me: () => request<Profile>("/v1/me"),
  updateMe: (body: { full_name?: string }) =>
    request<Profile>("/v1/me", { method: "PATCH", body: JSON.stringify(body) }),

  // the founder's bag designer (the API answers 404 to everyone else)
  designTemplates: () =>
    request<{
      templates: DesignTemplate[];
      max_colors: number;
      fonts?: { key: string; label: string; default: boolean }[];
      image_models?: Record<string, ImageModelTier>;
      infographic_models?: ImageModelTier;
      images_available?: boolean;
      pdf_available: boolean;
    }>(
      "/v1/design/templates",
    ),
  designSlideTemplates: () =>
    request<{
      templates: DesignTemplate[];
      max_colors: number;
      fonts: string[];
      image_models: Record<string, ImageModelTier>;
      infographic_models?: ImageModelTier;
      images_available: boolean;
      pdf_available: boolean;
    }>("/v1/design/slide-templates"),
  designSlideImages: (runId: string) =>
    request<SlideImages>(`/v1/runs/${runId}/design-slides/images`),
  designBookTemplates: () => request<BookCatalog>("/v1/design/book-templates"),
  designBookImages: (runId: string) =>
    request<{ saved: SavedImages | null }>(`/v1/runs/${runId}/design-book/images`),
  /* What this account chose the last time it designed this run. */
  designPrefs: (runId: string) =>
    request<{ designer?: string; colors?: string[]; author?: string; org_name?: string;
              font?: string }>(`/v1/runs/${runId}/design/prefs`),
  designImages: (runId: string) =>
    request<{
      saved: SavedImages | null;
      infographics?: SavedImages | null;
      infographic_candidates?: number;
      infographic_limit?: number;
    }>(`/v1/runs/${runId}/design/images`),
  designRuns: (q = "") =>
    request<{ items: DesignableRun[] }>(`/v1/design/runs?q=${encodeURIComponent(q)}`),

  // pipelines
  pipelines: () => request<{ items: PipelineDef[] }>("/v1/pipelines"),

  readBlueprint: (body: { pipeline_key: string; text: string; upload_ids: string[] }) =>
    request<BlueprintReading>("/v1/blueprint/read", { method: "POST", body: JSON.stringify(body) }),

  // projects
  projects: (params: { kind?: string; archived?: boolean } = {}) => {
    const q = new URLSearchParams();
    if (params.kind) q.set("kind", params.kind);
    if (params.archived !== undefined) q.set("archived", String(params.archived));
    return request<{ items: Project[]; total: number }>(`/v1/projects?${q}`);
  },
  project: (id: string) => request<Project>(`/v1/projects/${id}`),
  createProject: (body: {
    kind: string;
    title: string;
    description?: string;
    language?: string;
  }) => request<Project>("/v1/projects", { method: "POST", body: JSON.stringify(body) }),
  updateProject: (id: string, body: Record<string, unknown>) =>
    request<Project>(`/v1/projects/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
  deleteProject: (id: string) => request<void>(`/v1/projects/${id}`, { method: "DELETE" }),

  // runs
  runs: (projectId: string) =>
    request<{ items: Run[]; total: number }>(`/v1/projects/${projectId}/runs`),
  run: (id: string) => request<RunDetail>(`/v1/runs/${id}`),
  startRun: (
    projectId: string,
    body: {
      params: Record<string, unknown>;
      skip_steps?: string[];
      profile_id?: string | null;
    },
  ) =>
    request<Run>(`/v1/projects/${projectId}/runs`, {
      method: "POST",
      body: JSON.stringify(body),
    }),
  // The blueprint gate. Saving and approving are separate so a long edit is
  // never lost, but approve also accepts the edit so the screen can do both in
  // one call rather than leaving a window between them.
  review: (id: string) => request<ReviewPayload>(`/v1/runs/${id}/review`),
  saveReview: (id: string, blueprint: Record<string, unknown>) =>
    request<{ saved: boolean }>(`/v1/runs/${id}/review`, {
      method: "PATCH",
      body: JSON.stringify({ blueprint }),
    }),
  approveReview: (id: string, blueprint?: Record<string, unknown>) =>
    request<Run>(`/v1/runs/${id}/approve`, {
      method: "POST",
      body: JSON.stringify(blueprint ? { blueprint } : {}),
    }),
  // ยซุงุณุชูˆุฏูŠูˆ ุงู„ุฑูˆุงูŠุฉยป - the novel's studio (api/v1/novel.py)
  novelCatalog: () => request<NovelCatalog>("/v1/novel/catalog"),
  novelOutlineCheck: (plan: Record<string, unknown>) =>
    request<OutlineReport>("/v1/novel/outline-check", { method: "POST", body: JSON.stringify({ plan }) }),
  novelRegenerate: (id: string, n: number, plan: Record<string, unknown>, note = "") =>
    request<{ chapter: Record<string, unknown>; effects: string[]; check: OutlineReport }>(
      `/v1/runs/${id}/novel/chapters/${n}/regenerate`,
      { method: "POST", body: JSON.stringify({ plan, note }) }),
  novelWorkspace: (id: string) => request<NovelWorkspace>(`/v1/runs/${id}/novel/workspace`),
  novelAction: (id: string, n: number, action: string, note = "", confirm = false) =>
    request<NovelWorkspace & { affected?: number[] }>(`/v1/runs/${id}/novel/chapters/${n}/action`, {
      method: "POST", body: JSON.stringify({ action, note, confirm }),
    }),
  novelCheck: (id: string, n: number) =>
    request<NovelWorkspace & { findings: string[] }>(`/v1/runs/${id}/novel/chapters/${n}/check`, { method: "POST" }),
  novelApprove: (id: string, n: number) =>
    request<NovelWorkspace>(`/v1/runs/${id}/novel/chapters/${n}/approve`, { method: "POST" }),
  novelRestore: (id: string, n: number, version: number, confirm = false) =>
    request<NovelWorkspace>(`/v1/runs/${id}/novel/chapters/${n}/restore`, {
      method: "POST", body: JSON.stringify({ version, confirm }),
    }),
  novelQuality: (id: string) => request<NovelWorkspace>(`/v1/runs/${id}/novel/quality`, { method: "POST" }),
  novelExport: (id: string) =>
    request<{ files: { id: string; kind: string; format: string }[]; pdf: boolean; note: string }>(
      `/v1/runs/${id}/novel/export`, { method: "POST" }),
  /** The run's own record, from `offset` bytes on. The caller passes back the
      offset it was handed, so each poll carries only what is new. */
  runLog: (id: string, offset: number) =>
    request<{ text: string; offset: number }>(`/v1/runs/${id}/log?offset=${offset}`),

  resumeRun: (id: string) => request<Run>(`/v1/runs/${id}/resume`, { method: "POST" }),
  cancelRun: (id: string) => request<Run>(`/v1/runs/${id}/cancel`, { method: "POST" }),
  stepOutput: (runId: string, stepKey: string) =>
    request<{ step_key: string; status: string; output: unknown }>(
      `/v1/runs/${runId}/steps/${stepKey}/output`,
    ),

  // artifacts
  artifacts: (projectId: string) =>
    request<{ items: ArtifactMeta[] }>(`/v1/projects/${projectId}/artifacts`),
  /** The raw URL. Only useful with an Authorization header - see
   *  downloadArtifact / viewArtifact below, which is how the UI reaches it. */
  artifactUrl: (id: string) => `${API_URL}/v1/artifacts/${id}`,

  // uploads
  uploads: (projectId: string) =>
    request<{ items: UploadMeta[] }>(`/v1/projects/${projectId}/uploads`),
  deleteUpload: (id: string) => request<void>(`/v1/uploads/${id}`, { method: "DELETE" }),
  /** how the file was read, and the start of its text */
  upload: (id: string, preview = 0) =>
    request<UploadMeta>(`/v1/uploads/${id}?preview=${preview}`),
  /** read the file again, every page by OCR */
  rereadUpload: (id: string) =>
    request<UploadMeta>(`/v1/uploads/${id}/read?force_ocr=true`, { method: "POST" }),

  // task types (the spec's name for a pipeline)
  taskTypes: () => request<{ items: TaskType[] }>("/v1/task-types"),
  taskType: (id: string) => request<TaskType>(`/v1/task-types/${id}`),

  // profiles - saved context
  profileSchema: () => request<JsonSchema>("/v1/profiles/schema"),
  profiles: () => request<{ items: SavedProfile[] }>("/v1/profiles"),
  createProfile: (body: ProfileInput) =>
    request<SavedProfile>("/v1/profiles", { method: "POST", body: JSON.stringify(body) }),
  updateProfile: (id: string, body: ProfileInput) =>
    request<SavedProfile>(`/v1/profiles/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
  deleteProfile: (id: string) =>
    request<{ archived: boolean; usedByRuns: number }>(`/v1/profiles/${id}`, { method: "DELETE" }),

  // library and usage
  library: (params: Record<string, string> = {}) =>
    request<{ items: LibraryItem[]; total: number }>(
      `/v1/library?${new URLSearchParams(params)}`,
    ),
  usage: () => request<UsageSummary>("/v1/usage"),
  announcements: () => request<{ items: AnnouncementItem[] }>("/v1/announcements"),

  // admin
  // user administration
  /* The public catalogue. Slim on purpose: `/v1/pipelines` carries a JSON
     Schema for every step and runs to 108 KB, which the wizard needs and the
     front page does not. */
  catalogue: () => request<{ items: CatalogueEntry[] }>("/v1/catalogue"),

  adminPendingUsers: () => request<AdminUserRow[]>("/v1/admin/users/pending"),
  approveUser: (
    id: string,
    body: {
      allowed_task_types: string[];
      department?: string | null;
      make_admin?: boolean;
      design_access?: string[];
    },
  ) =>
    request<Profile>(`/v1/admin/users/${id}/approve`, {
      method: "POST",
      body: JSON.stringify(body),
    }),
  deleteUser: (id: string) =>
    request<void>(`/v1/admin/users/${id}`, { method: "DELETE" }),
  /* The founder's alone: which designers an account may use. */
  setDesignAccess: (id: string, designs: string[]) =>
    request<{ design_access: string[] }>(`/v1/admin/users/${id}/design-access`, {
      method: "PUT",
      body: JSON.stringify({ design_access: designs }),
    }),
  /* Generated and handed over, never mailed - see the endpoint's own note. */
  userResetLink: (id: string) =>
    request<{ email: string; link: string; expires_in_minutes: number }>(
      `/v1/admin/users/${id}/reset-link`,
      { method: "POST" },
    ),
  patchUser: (
    id: string,
    body: {
      status?: string;
      role?: string;
      department?: string;
      allowed_task_types?: string[];
      monthly_cost_limit_usd?: number | null;
    },
  ) =>
    request<Profile>(`/v1/admin/users/${id}`, {
      method: "PATCH",
      body: JSON.stringify(body),
    }),
  /** One person, whole: totals, tools, and the named list of what they made. */
  userDetail: (id: string, days: number) =>
    request<UserDetail>(`/v1/admin/users/${id}/detail?days=${days}`),
  userByTaskType: (id: string, days: number) =>
    request<TaskTypeSpend[]>(`/v1/admin/users/${id}/by-task-type?days=${days}`),
  usageMatrix: (days: number) =>
    request<UsageMatrix>(`/v1/admin/usage/matrix?days=${days}`),

  adminTaskTypes: () => request<{ items: TaskType[] }>("/v1/admin/task-types"),
  adminPatchTaskType: (id: string, body: Record<string, unknown>) =>
    request<TaskType>(`/v1/admin/task-types/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
  adminAnnouncements: () => request<{ items: AdminAnnouncement[] }>("/v1/admin/announcements"),
  adminCreateAnnouncement: (body: Record<string, unknown>) =>
    request<{ id: string }>("/v1/admin/announcements", { method: "POST", body: JSON.stringify(body) }),
  adminPatchAnnouncement: (id: string, body: { published?: boolean; body?: string }) =>
    request<{ id: string; published: boolean }>(`/v1/admin/announcements/${id}`, {
      method: "PATCH",
      body: JSON.stringify(body),
    }),
  adminDeleteAnnouncement: (id: string) =>
    request<void>(`/v1/admin/announcements/${id}`, { method: "DELETE" }),
  adminAudit: (params: Record<string, string> = {}) =>
    request<{ items: AuditEntry[] }>(`/v1/admin/audit?${new URLSearchParams(params)}`),
  adminRunDetail: (id: string) => request<AdminRunDetail>(`/v1/admin/runs/${id}`),
  adminRetryRun: (id: string) =>
    request<{ status: string }>(`/v1/admin/runs/${id}/retry`, { method: "POST" }),
  adminImpersonate: (id: string) =>
    request<{ userId: string; email: string; note: string }>(
      `/v1/admin/users/${id}/impersonate`, { method: "POST" },
    ),
  adminOverview: () => request<AdminOverview>("/v1/admin/overview"),
  /* Our ledger beside the provider's, so a gap is visible rather than
     assumed. The dashboard cannot otherwise tell you it under-counted. */
  adminReconciliation: () => request<Reconciliation>("/v1/admin/reconciliation"),
  // 500, the endpoint's ceiling: the users screen groups and ranks everyone.
  adminUsers: (sort = "cost", limit = 500) =>
    request<UserUsage[]>(`/v1/admin/users?sort=${sort}&limit=${limit}`),
  adminPatchUser: (id: string, body: Record<string, unknown>) =>
    request<Profile>(`/v1/admin/users/${id}`, { method: "PATCH", body: JSON.stringify(body) }),
  adminSeries: (days = 30) => request<SeriesPoint[]>(`/v1/admin/usage/series?days=${days}`),
  adminByModel: (days = 30) => request<ModelBreakdown[]>(`/v1/admin/usage/by-model?days=${days}`),
  adminByPipeline: (days = 30) =>
    request<PipelineBreakdown[]>(`/v1/admin/usage/by-pipeline?days=${days}`),
  adminRuns: (status?: string) =>
    request<{ items: AdminRun[] }>(`/v1/admin/runs${status ? `?status=${status}` : ""}`),
  adminFailures: (days = 30) =>
    request<{
      runs_total: number;
      runs_succeeded: number;
      runs_failed: number;
      success_rate: number | null;
      by_step: { step_key: string; failures: number }[];
    }>(`/v1/admin/runs/failures?days=${days}`),
};

/** Live run progress over SSE.
 *
 * EventSource cannot send an Authorization header, so this uses fetch with a
 * reader instead. Returns a function that stops the stream.
 */
export function streamRun(
  runId: string,
  onEvent: (event: string, data: unknown) => void,
): () => void {
  const controller = new AbortController();

  (async () => {
    const res = await fetch(`${API_URL}/v1/runs/${runId}/events`, {
      headers: { ...(await authHeader()) },
      signal: controller.signal,
    });
    if (!res.body) return;

    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      // SSE frames are separated by a blank line.
      const frames = buffer.split("\n\n");
      buffer = frames.pop() ?? "";
      for (const frame of frames) {
        let event = "message";
        let data = "";
        for (const line of frame.split("\n")) {
          if (line.startsWith("event:")) event = line.slice(6).trim();
          else if (line.startsWith("data:")) data += line.slice(5).trim();
        }
        if (!data) continue;
        try {
          onEvent(event, JSON.parse(data));
        } catch {
          onEvent(event, data);
        }
      }
    }
  })().catch((e) => {
    if ((e as Error).name !== "AbortError") console.warn("run stream ended", e);
  });

  return () => controller.abort();
}


/** Upload a source file. Uses FormData, so the JSON content-type must not be
 *  set - the browser has to write its own multipart boundary. */
export async function uploadSource(projectId: string, file: File, read = true): Promise<UploadMeta> {
  const body = new FormData();
  body.append("file", file);

  const res = await fetch(`${API_URL}/v1/projects/${projectId}/uploads${read ? "" : "?read=false"}`, {
    method: "POST",
    headers: await authHeader(),
    body,
  });

  if (!res.ok) {
    let message = `ุชุนุฐู‘ุฑ ุฑูุน ุงู„ู…ู„ู (${res.status})`;
    try {
      const payload = await res.json();
      if (typeof payload?.detail === "string") message = payload.detail;
    } catch {
      /* keep the fallback */
    }
    throw new ApiError(res.status, message);
  }
  return res.json() as Promise<UploadMeta>;
}


/** Design a finished Arabic bag: template, up to four colours, a logo.
 *  Multipart, so the JSON content-type is left for the browser to set. */
export async function designRun(
  runId: string,
  form: {
    template: string;
    colors: string[];
    author: string;
    orgName: string;
    showImageSlots: boolean;
    font: string;
    images: "none" | "saved" | "generate";
    imageStyle?: "vector" | "natural";
    models: Record<string, string>;
    infographics?: "none" | "saved" | "generate";
    infographicCount?: number;
    infographicModel?: string;
    logo: File | null;
  },
): Promise<DesignResult> {
  const body = new FormData();
  body.append("template", form.template);
  body.append("colors", JSON.stringify(form.colors));
  body.append("author", form.author);
  body.append("org_name", form.orgName);
  body.append("show_image_slots", String(form.showImageSlots));
  body.append("font", form.font);
  body.append("images", form.images);
  body.append("image_style", form.imageStyle ?? "vector");
  for (const [tier, key] of Object.entries(form.models)) body.append(`model_${tier}`, key);
  body.append("infographics", form.infographics ?? "none");
  body.append("infographic_count", String(form.infographicCount ?? 0));
  if (form.infographicModel) body.append("model_infographic", form.infographicModel);
  if (form.logo) body.append("logo", form.logo);

  const res = await fetch(`${API_URL}/v1/runs/${runId}/design`, {
    method: "POST",
    headers: await authHeader(),
    body,
  });
  if (!res.ok) {
    let message = `ุชุนุฐู‘ุฑ ุชุตู…ูŠู… ุงู„ุญู‚ูŠุจุฉ (${res.status})`;
    try {
      const payload = await res.json();
      if (typeof payload?.detail === "string") message = payload.detail;
    } catch {
      /* keep the fallback */
    }
    throw new ApiError(res.status, message);
  }
  return res.json() as Promise<DesignResult>;
}


/** Design a run's slides - a bag's deck or a standalone deck - as PowerPoint. */
export async function designSlides(
  runId: string,
  form: {
    template: string;
    colors: string[];
    author: string;
    orgName: string;
    font: string;
    logo: File | null;
    images?: "none" | "saved" | "bag" | "generate";
    scope?: "main" | "all";
    models?: Record<string, string>;
    infographics?: "none" | "saved" | "generate";
    infographicCount?: number;
    infographicModel?: string;
    activityPictures?: boolean;
    still?: boolean;
    imageTreatment?: "grayscale" | "duotone" | "color";
  },
): Promise<SlideDesignResult> {
  const body = new FormData();
  body.append("template", form.template);
  body.append("colors", JSON.stringify(form.colors));
  body.append("author", form.author);
  body.append("org_name", form.orgName);
  body.append("font", form.font);
  body.append("images", form.images ?? "none");
  body.append("scope", form.scope ?? "all");
  body.append("infographics", form.infographics ?? "none");
  body.append("infographic_count", String(form.infographicCount ?? 0));
  if (form.infographicModel) body.append("model_infographic", form.infographicModel);
  for (const [tier, key] of Object.entries(form.models ?? {})) body.append(`model_${tier}`, key);
  body.append("activity_pictures", String(Boolean(form.activityPictures)));
  body.append("still", String(Boolean(form.still)));
  if (form.imageTreatment) body.append("image_treatment", form.imageTreatment);
  if (form.logo) body.append("logo", form.logo);

  const res = await fetch(`${API_URL}/v1/runs/${runId}/design-slides`, {
    method: "POST",
    headers: await authHeader(),
    body,
  });
  if (!res.ok) {
    let message = `ุชุนุฐู‘ุฑ ุชุตู…ูŠู… ุงู„ุนุฑุถ (${res.status})`;
    try {
      const payload = await res.json();
      if (typeof payload?.detail === "string") message = payload.detail;
    } catch {
      /* keep the fallback */
    }
    throw new ApiError(res.status, message);
  }
  return res.json() as Promise<SlideDesignResult>;
}


/* Artifacts need the Authorization header, which a plain <a href> cannot send.
   Linking straight at the endpoint therefore produced a 401 page instead of a
   file. These fetch it properly and hand the browser a blob. */

async function fetchArtifact(id: string): Promise<Blob> {
  const res = await fetch(`${API_URL}/v1/artifacts/${id}`, {
    headers: await authHeader(),
  });
  if (!res.ok) {
    throw new ApiError(res.status, `ุชุนุฐู‘ุฑ ุฌู„ุจ ุงู„ู…ู„ู (${res.status})`);
  }
  return res.blob();
}

function safeName(title: string, format: string): string {
  const base = (title || "ู…ุฎุฑุฌ").replace(/[/:*?"<>|]/g, "-").slice(0, 80);
  return `${base}.${format.toLowerCase()}`;
}

/** Save the artifact to disk under a readable name. */
export async function downloadArtifact(
  id: string,
  title: string,
  format: string,
): Promise<void> {
  const blob = await fetchArtifact(id);
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = safeName(title, format);
  document.body.appendChild(link);
  link.click();
  link.remove();
  // Revoked on the next tick: Firefox cancels the download if it goes early.
  setTimeout(() => URL.revokeObjectURL(url), 10_000);
}

/** The file name the server gave the gate's Word file (RFC 5987 `filename*`),
 *  or ยซุงู„ุชุตูˆุฑ ุงู„ูู†ูŠ.docxยป when it gave none. */
export function reviewFileName(disposition: string | null): string {
  const m = /filename\*=UTF-8''([^;]+)/i.exec(disposition || "");
  if (m) {
    try {
      const name = decodeURIComponent(m[1].trim());
      if (name.toLowerCase().endsWith(".docx")) return safeName(name.slice(0, -5), "docx");
    } catch {
      /* a malformed header falls back to the plain name */
    }
  }
  return safeName("ุงู„ุชุตูˆุฑ ุงู„ูู†ูŠ", "docx");
}

/** Save the blueprint waiting at the gate as a Word file.

   The reviewer is being asked whether the structure holds together, and a form
   is the wrong shape for that question: it shows one field at a time and never
   the whole thing in order. Rendered server-side from what the run is holding,
   so a saved edit is already in it. */
export async function downloadBlueprint(runId: string): Promise<void> {
  const res = await fetch(`${API_URL}/v1/runs/${runId}/review.docx`, {
    headers: await authHeader(),
  });
  if (!res.ok) {
    throw new ApiError(res.status, `ุชุนุฐู‘ุฑ ุชุฌู‡ูŠุฒ ุงู„ู…ู„ู (${res.status})`);
  }
  const url = URL.createObjectURL(await res.blob());
  const link = document.createElement("a");
  link.href = url;
  // named after the book or bag it holds (the server says so), not
  // ยซุงู„ุชุตูˆุฑ ุงู„ูู†ูŠยป again for the browser to number ยซ(9)ยป
  link.download = reviewFileName(res.headers.get("Content-Disposition"));
  document.body.appendChild(link);
  link.click();
  link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 10_000);
}

/** Open an HTML report in a new tab. */
/** A fixed example of a book template and weight, opened in a new tab -
 *  drawn from the demo book on the server, no model called. */
export async function viewBookExample(template: string, tier: string, trim: string): Promise<void> {
  const tab = window.open("", "_blank");
  try {
    const q = new URLSearchParams({ template, tier, trim });
    const res = await fetch(`${API_URL}/v1/design/book-example?${q}`, { headers: await authHeader() });
    if (!res.ok) throw new ApiError(res.status, `ุชุนุฐู‘ุฑ ูุชุญ ุงู„ู†ู…ูˆุฐุฌ (${res.status})`);
    const url = URL.createObjectURL(await res.blob());
    if (tab) tab.location.href = url;
    else window.location.href = url;
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  } catch (e) {
    tab?.close();
    throw e;
  }
}

/** Design a finished book: the sample for the client, or the whole book. */
export async function designBook(
  runId: string,
  form: Record<string, string | boolean | string[]>,
  logo: File | null,
): Promise<BookDesignResult> {
  const body = new FormData();
  for (const [k, v] of Object.entries(form)) {
    body.append(k, Array.isArray(v) ? JSON.stringify(v) : String(v));
  }
  if (logo) body.append("logo", logo);
  const res = await fetch(`${API_URL}/v1/runs/${runId}/design-book`, {
    method: "POST",
    headers: await authHeader(),
    body,
  });
  if (!res.ok) {
    let message = `ุชุนุฐู‘ุฑ ุชุตู…ูŠู… ุงู„ูƒุชุงุจ (${res.status})`;
    try {
      const payload = await res.json();
      if (typeof payload?.detail === "string") message = payload.detail;
    } catch {
      /* keep the fallback */
    }
    throw new ApiError(res.status, message);
  }
  return res.json();
}

export async function viewArtifact(id: string): Promise<void> {
  // The tab is opened synchronously, before the await, or the pop-up blocker
  // treats it as unrelated to the click that caused it.
  const tab = window.open("", "_blank");
  try {
    const blob = await fetchArtifact(id);
    const url = URL.createObjectURL(blob);
    if (tab) {
      tab.location.href = url;
    } else {
      window.location.href = url;
    }
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  } catch (e) {
    tab?.close();
    throw e;
  }
}

// โ”€โ”€ ยซุงุณุชูˆุฏูŠูˆ ุงู„ุฑูˆุงูŠุฉยป types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
export type NovelCatalog = Record<string, Record<string, [string, string]>>;
export type OutlineItem = { key: string; question: string; ok: boolean; note: string };
export type OutlineReport = {
  items: OutlineItem[]; passed: number; total: number;
  cards: { chapter: number; missing: string[] }[]; events_missing: string[];
  acts: Record<string, number[]>;
};
export type NovelChapter = {
  number: number; title: string; status: string; status_ar: string;
  card: Record<string, unknown>; text: string; summary: string; words: number; current: number;
  attention: string[]; check: string[];
  versions: { index: number; source: string; at: string; words: number }[];
};
export type NovelQualityRow = {
  key: string; name: string; weight: number; core: boolean; score: number | null; reason: string;
  strengths: string[]; weaknesses: string[]; recommendations: string[]; chapters: number[];
};
export type NovelWorkspace = {
  title: string; author: string; chapters: NovelChapter[]; memory: Record<string, unknown>;
  quality: null | { verdict?: string; quality?: { total: number | null; level: string; warning: string;
    criteria: NovelQualityRow[]; revisit: number[]; metrics: Record<string, number> } };
  counts: Record<string, number>; actions: Record<string, string>;
  history: { chapter: number; event: string; at: string }[];
};