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
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
// apps/api/src/routes/analysis.ts
// Seven REST endpoints under /api/analysis. All responses use the standard
// envelope { code, msg, data? } per the system contract.

import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { basename, join } from "node:path";
import { mkdirSync, writeFileSync, existsSync, createReadStream } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import JSZip from "jszip";

import type { Config } from "../config.js";
import type { Store, ItemRow } from "../queue/store.js";
import type { QueueRunner, OptionsSnapshot } from "../queue/runner.js";
import { detectModeFromZip } from "../analyzers/detect.js";

interface RouteDeps {
  store: Store;
  config: Config;
  runner: QueueRunner;
}

const ZIP_FILENAME_RE = /\.zip$/i;

function boundedNumber(min: number, max: number) {
  return z.preprocess((value) => {
    if (value === undefined) return value;
    const parsed = Number(value);
    if (!Number.isFinite(parsed)) return value;
    return Math.min(max, Math.max(min, parsed));
  }, z.number().min(min).max(max));
}

function boundedInteger(min: number, max: number) {
  return z.preprocess((value) => {
    if (value === undefined) return value;
    const parsed = Number(value);
    if (!Number.isFinite(parsed)) return value;
    return Math.min(max, Math.max(min, Math.round(parsed)));
  }, z.number().int().min(min).max(max));
}

// Whitelist of fields accepted for optionsSnapshot. The frontend is permitted
// to override the main analyzer model's API key (used for recommended_groups
// + recommended_rubrics generation). Judge keys remain backend-only via .env.
const OptionsSnapshotSchema = z
  .object({
    requestedMode: z.enum(["api", "mcp"]).optional(),
    model: z.string().optional(),
    baseURL: z.string().optional(),
    apiKey: z.string().optional(),
    apiMode: z.enum(["chat", "responses"]).optional(),
    concurrency: boundedInteger(1, 8).optional(),
    temperature: boundedNumber(0, 2).optional(),
    topP: boundedNumber(0, 1).optional(),
    maxTokens: boundedInteger(1, 131072).optional(),
    streaming: z.boolean().optional(),
    enableThinking: z.boolean().optional(),
    clearThinking: z.boolean().optional(),
    ruleProfile: z.string().optional(),
    optimizeTask: z.boolean().optional(),
    feedback: z.string().optional(),
    strictFullMarks: z.boolean().optional(),
    ignoreTaskComplexityForFullMarks: z.boolean().optional(),
    judge: z
      .object({
        model: z.string().optional(),
        baseURL: z.string().optional(),
        apiMode: z.enum(["chat", "responses"]).optional(),
        promptTemplate: z.string().optional(),
      })
      .strict()
      .optional(),
    rubricGeneration: z
      .object({
        model: z.string().optional(),
        baseURL: z.string().optional(),
        apiMode: z.enum(["chat", "responses"]).optional(),
      })
      .strict()
      .optional(),
  })
  .strict();

function ok(data: unknown) {
  return { code: 0, msg: "ok", data };
}

function errEnv(code: number, msg: string) {
  return { code, msg };
}

function publicItemView(row: ItemRow) {
  const progressByStatus: Record<string, number> = {
    queued: 0,
    running: 0.35,
    judging: 0.75,
    completed: 1,
    failed: 1,
    stopped: 1,
  };
  return {
    id: row.id,
    jobId: row.job_id,
    ord: row.ord,
    filename: row.filename,
    detectedMode: row.detected_mode,
    status: row.status,
    progress: progressByStatus[row.status] ?? 0,
    errorPreview: row.error_preview,
    attemptCount: row.attempt_count,
    lastStage: row.last_stage,
    hasExport: Boolean(row.export_zip_path),
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  };
}

function attachmentHeader(filename: string): string {
  let fallback = basename(filename)
    .replace(/[^\w.-]+/g, "_")
    .replace(/^_+|_+$/g, "");
  if (!fallback || fallback.startsWith(".")) fallback = "download.zip";
  return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
}

async function readJsonArtifact(path: string | null): Promise<unknown | null> {
  if (!path || !existsSync(path)) return null;
  return JSON.parse(await readFile(path, "utf8"));
}

function finiteNumber(value: unknown): number | null {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : null;
}

async function readJudgeHistory(config: Config, item: ItemRow) {
  const itemDir = join(config.exportDir, item.job_id, item.id);
  let entries: string[];
  try {
    entries = await readdir(itemDir);
  } catch {
    return [];
  }

  const files = entries
    .map((name) => {
      const match = /^judge-result-iter-(\d+)\.json$/.exec(name);
      return match ? { name, iteration: Number(match[1]) } : null;
    })
    .filter((entry): entry is { name: string; iteration: number } => Boolean(entry))
    .sort((a, b) => a.iteration - b.iteration);

  const history = [];
  for (const file of files) {
    const judgeResult = await readJsonArtifact(join(itemDir, file.name));
    if (!judgeResult || typeof judgeResult !== "object") continue;
    const result = judgeResult as Record<string, unknown>;
    history.push({
      iteration: file.iteration,
      score: finiteNumber(result.total_score),
      maxScore: finiteNumber(result.max_score) ?? 12,
      verdict: typeof result.verdict === "string" ? result.verdict : "",
      hasZeros: Boolean(result.has_zeros),
      judgeResult: result,
    });
  }
  return history;
}

interface PendingUpload {
  filename: string;
  buffer: Buffer;
  autoDetectedMode: "api" | "mcp";
}

function normalizeRequestedMode(value: unknown): "api" | "mcp" | null {
  return value === "api" || value === "mcp" ? value : null;
}

export async function registerAnalysisRoutes(
  app: FastifyInstance,
  deps: RouteDeps
): Promise<void> {
  const { store, config, runner } = deps;

  // โ”€โ”€ POST /api/analysis/jobs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  // Multipart upload: 1..N .zip files. The selected page can force api/mcp
  // mode via requestedMode; otherwise each zip is auto-detected.
  app.post("/api/analysis/jobs", async (req, reply) => {
    if (!req.isMultipart()) {
      reply.code(400).send(errEnv(400, "Expected multipart/form-data"));
      return;
    }

    // Step 1: read + validate all parts in memory (bounded by maxUploadMB +
    // maxBatchFiles via fastify-multipart limits).
    const pending: PendingUpload[] = [];
    let requestedMode: "api" | "mcp" | null = null;
    try {
      const parts = req.parts();
      for await (const part of parts) {
        if (part.type === "field") {
          if (part.fieldname === "requestedMode") {
            const normalized = normalizeRequestedMode(part.value);
            if (!normalized) {
              reply.code(400).send(errEnv(400, "requestedMode ๅช่ƒฝๆ˜ฏ api ๆˆ– mcp"));
              return;
            }
            requestedMode = normalized;
          }
          continue;
        }
        if (!part.filename) continue;
        if (!ZIP_FILENAME_RE.test(part.filename)) {
          reply.code(400).send(errEnv(400, `ไป…ๆ”ฏๆŒ .zip ๆ–‡ไปถ๏ผš${part.filename}`));
          return;
        }
        const buf = await part.toBuffer();
        let detected: { mode: "api" | "mcp" };
        try {
          detected = await detectModeFromZip(buf);
        } catch (e) {
          const msg = e instanceof Error ? e.message : "ZIP ๆ ก้ชŒๅคฑ่ดฅ";
          reply.code(400).send(errEnv(400, `${part.filename}: ${msg}`));
          return;
        }
        pending.push({
          filename: part.filename,
          buffer: buf,
          autoDetectedMode: detected.mode,
        });
      }
    } catch (e) {
      app.log.error({ err: e }, "Failed to consume multipart upload");
      reply.code(500).send(errEnv(500, "ไธŠไผ ่ฏปๅ–ๅคฑ่ดฅ"));
      return;
    }

    if (pending.length === 0) {
      reply.code(400).send(errEnv(400, "ๆœชๆ”ถๅˆฐไปปไฝ• .zip ๆ–‡ไปถ"));
      return;
    }
    if (pending.length > config.maxBatchFiles) {
      reply
        .code(400)
        .send(
          errEnv(
            400,
            `ๅ•ๆฌกๆœ€ๅคšไธŠไผ  ${config.maxBatchFiles} ไธช zip๏ผŒๆœฌๆฌก๏ผš${pending.length}`
          )
        );
      return;
    }

    // Step 2: create job + persist files under canonical job dir.
    const job = await store.createJob({});
    const jobUploadDir = join(config.uploadDir, job.id);
    try {
      mkdirSync(jobUploadDir, { recursive: true });
    } catch (e) {
      app.log.error({ err: e, jobUploadDir }, "Failed to create upload dir");
      reply.code(500).send(errEnv(500, "ไธŠไผ ็›ฎๅฝ•ๅˆ›ๅปบๅคฑ่ดฅ"));
      return;
    }

    const itemRows: ItemRow[] = [];
    for (const [idx, p] of pending.entries()) {
      const uploadPath = join(jobUploadDir, `${randomUUID()}.zip`);
      writeFileSync(uploadPath, p.buffer);
      const row = await store.createItem({
        jobId: job.id,
        ord: idx + 1,
        filename: p.filename,
        uploadPath,
        detectedMode: requestedMode ?? p.autoDetectedMode,
      });
      itemRows.push(row);
    }

    reply.send(
      ok({
        jobId: job.id,
        items: itemRows.map(publicItemView),
      })
    );
  });

  // โ”€โ”€ GET /api/analysis/jobs/:jobId โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app.get<{ Params: { jobId: string } }>(
    "/api/analysis/jobs/:jobId",
    async (req, reply) => {
      const job = await store.getJob(req.params.jobId);
      if (!job) {
        reply.code(404).send(errEnv(404, "Job not found"));
        return;
      }
      const items = (await store.listItemsByJob(job.id)).map(publicItemView);
      reply.send(
        ok({
          id: job.id,
          status: job.status,
          createdAt: job.created_at,
          updatedAt: job.updated_at,
          items,
        })
      );
    }
  );

  // โ”€โ”€ POST /api/analysis/jobs/:jobId/start โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app.post<{
    Params: { jobId: string };
    Body: { optionsSnapshot?: unknown };
  }>("/api/analysis/jobs/:jobId/start", async (req, reply) => {
    const job = await store.getJob(req.params.jobId);
    if (!job) {
      reply.code(404).send(errEnv(404, "Job not found"));
      return;
    }
    if (job.status === "running") {
      reply.code(409).send(errEnv(409, "Job ๅทฒ็ปๅœจ่ฟ่กŒไธญ"));
      return;
    }

    const rawSnapshot =
      (req.body as { optionsSnapshot?: unknown } | undefined)?.optionsSnapshot ??
      {};
    const parsed = OptionsSnapshotSchema.safeParse(rawSnapshot);
    if (!parsed.success) {
      reply
        .code(400)
        .send(errEnv(400, `optionsSnapshot ๆ ก้ชŒๅคฑ่ดฅ๏ผš${parsed.error.message}`));
      return;
    }
    const snapshot: OptionsSnapshot = parsed.data;

    await store.updateJobOptions(job.id, snapshot);
    runner.scheduleJob(job.id);

    reply.send(ok({ jobId: job.id, status: "running" }));
  });

  // โ”€โ”€ POST /api/analysis/jobs/:jobId/cancel โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app.post<{ Params: { jobId: string } }>(
    "/api/analysis/jobs/:jobId/cancel",
    async (req, reply) => {
      const job = await store.getJob(req.params.jobId);
      if (!job) {
        reply.code(404).send(errEnv(404, "Job not found"));
        return;
      }
      runner.cancelJob(job.id);
      reply.send(ok({ jobId: job.id, status: "cancel-requested" }));
    }
  );

  // โ”€โ”€ POST /api/analysis/jobs/:jobId/items/:itemId/retry โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app.post<{ Params: { jobId: string; itemId: string } }>(
    "/api/analysis/jobs/:jobId/items/:itemId/retry",
    async (req, reply) => {
      const item = await store.getItem(req.params.itemId);
      if (!item || item.job_id !== req.params.jobId) {
        reply.code(404).send(errEnv(404, "Item not found"));
        return;
      }
      await runner.retryItem(item.id);
      reply.send(ok({ itemId: item.id, status: "queued" }));
    }
  );

  // โ”€โ”€ GET /api/analysis/jobs/:jobId/items/:itemId/result โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  // Returns the generated JSON artifacts so the frontend can render concrete
  // analysis details even though the heavy work runs in the backend.
  app.get<{ Params: { jobId: string; itemId: string } }>(
    "/api/analysis/jobs/:jobId/items/:itemId/result",
    async (req, reply) => {
      const item = await store.getItem(req.params.itemId);
      if (!item || item.job_id !== req.params.jobId) {
        reply.code(404).send(errEnv(404, "Item not found"));
        return;
      }

      try {
        const evidenceBundle = (await readJsonArtifact(item.evidence_path)) as
          | {
              flags?: unknown;
              evidence?: unknown;
              analyzerResult?: unknown;
              iterationMemory?: unknown;
            }
          | null;
        const taskPackage = await readJsonArtifact(item.task_package_path);
        const judgeHistory = await readJudgeHistory(config, item);
        const latestJudgeResult = judgeHistory.at(-1)?.judgeResult ?? null;
        const judgeResult = (await readJsonArtifact(item.judge_result_path)) ?? latestJudgeResult;
        reply.send(
          ok({
            item: publicItemView(item),
            flags: evidenceBundle?.flags ?? [],
            evidence: evidenceBundle?.evidence ?? null,
            analyzerResult: evidenceBundle?.analyzerResult ?? null,
            iterationMemory: evidenceBundle?.iterationMemory ?? null,
            taskPackage,
            judgeResult,
            judgeHistory,
          })
        );
      } catch (e) {
        app.log.error({ err: e, itemId: item.id }, "Failed to read item artifacts");
        reply.code(500).send(errEnv(500, "ๅˆ†ๆž็ป“ๆžœ่ฏปๅ–ๅคฑ่ดฅ"));
      }
    }
  );

  // โ”€โ”€ GET /api/analysis/jobs/:jobId/items/:itemId/download โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  app.get<{ Params: { jobId: string; itemId: string } }>(
    "/api/analysis/jobs/:jobId/items/:itemId/download",
    async (req, reply) => {
      const item = await store.getItem(req.params.itemId);
      if (!item || item.job_id !== req.params.jobId) {
        reply.code(404).send(errEnv(404, "Item not found"));
        return;
      }
      if (!item.export_zip_path || !existsSync(item.export_zip_path)) {
        reply.code(404).send(errEnv(404, "ๅฏผๅ‡บๆ–‡ไปถๅฐšๆœช็”Ÿๆˆ"));
        return;
      }
      const downloadName =
        item.filename.replace(ZIP_FILENAME_RE, "") + ".task-package.zip";
      reply
        .header("Content-Type", "application/zip")
        .header("Content-Disposition", attachmentHeader(downloadName));
      return reply.send(createReadStream(item.export_zip_path));
    }
  );

  // โ”€โ”€ GET /api/analysis/jobs/:jobId/download-all โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  // Bundles all completed items into a single zip-of-zips on the fly.
  app.get<{ Params: { jobId: string } }>(
    "/api/analysis/jobs/:jobId/download-all",
    async (req, reply) => {
      const job = await store.getJob(req.params.jobId);
      if (!job) {
        reply.code(404).send(errEnv(404, "Job not found"));
        return;
      }
      const items = await store.listItemsByJob(job.id);
      const exportable = items.filter(
        (it) => it.export_zip_path && existsSync(it.export_zip_path)
      );
      if (exportable.length === 0) {
        reply.code(404).send(errEnv(404, "ๆš‚ๆ— ๅฏไธ‹่ฝฝ็š„ๅฏผๅ‡บ้กน"));
        return;
      }

      const zip = new JSZip();
      const used = new Set<string>();
      for (const it of exportable) {
        const baseName =
          it.filename.replace(ZIP_FILENAME_RE, "") + ".task-package.zip";
        let entryName = baseName;
        let i = 1;
        while (used.has(entryName)) {
          entryName = `${baseName.replace(/\.task-package\.zip$/i, "")}-${i}.task-package.zip`;
          i += 1;
        }
        used.add(entryName);
        const content = await readFile(it.export_zip_path!);
        zip.file(entryName, content);
      }
      const buf = await zip.generateAsync({
        type: "nodebuffer",
        compression: "DEFLATE",
        compressionOptions: { level: 6 },
      });
      reply
        .header("Content-Type", "application/zip")
        .header(
          "Content-Disposition",
          attachmentHeader(`all-results-${job.id.slice(0, 8)}.zip`)
        );
      reply.send(buf);
    }
  );
}