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
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
import {
  delay,
  demoUser,
} from "@/lib/frontend-demo-data";
import {
  getLocalPreviousPaperAnalysis,
  getLocalPreviousPapers,
  getLocalPreviousQuestions,
  saveLocalPreviousPaper,
} from "@/lib/frontend-local-store";
import { apiGet, apiPost, apiUpload } from "@/lib/api/client";
import { shouldUseDemoData, withDemoFallback } from "@/lib/api/mode";
import type {
  LocalOfflinePreviousPaper,
  PreviousPaper,
  PreviousPaperAnalysisResponse,
  PreviousPaperUploadInput,
  PreviousQuestion,
  PreviousQuestionExtractRequest,
  PreviousQuestionExtractResponse,
  StructuredPreviousPaperAnalyzeRequest,
} from "@/lib/api/types";

export type PYQDiscoveryCandidate = {
  title: string;
  url: string;
  snippet: string;
  year: number | null;
  subject: string | null;
  board: string | null;
  class_level: string | null;
  source_domain: string;
  source_title: string | null;
  confidence_score: number;
  official_source: boolean;
  file_hash: string | null;
  notes: string | null;
  warnings: string[];
};

export type PYQDiscoverySearchPayload = {
  board?: string | null;
  class_level?: string | null;
  subject?: string | null;
  year_start?: number | null;
  year_end?: number | null;
  manual_urls?: string[];
};

export type PYQDiscoverySearchResponse = {
  enabled: boolean;
  provider: string;
  configured: boolean;
  message: string;
  candidates: PYQDiscoveryCandidate[];
};

export type PYQDiscoveryImportResponse = {
  id: string;
  title: string;
  year: number | null;
  subject: string | null;
  verification_status: string;
  confidence_score: number | null;
  official_source: boolean;
  source_url: string | null;
  deduped: boolean;
};

export type PyqAnalysisRequest = {
  subject?: string | null;
  board?: string | null;
  class_level?: string | null;
  exam?: string | null;
  chapter?: string | null;
  topic?: string | null;
  paper_ids?: string[];
  source_id?: string | null;
  years?: number[];
};

export type PyqAnalysis = {
  available: boolean;
  status: "available" | "unavailable" | "awaiting_verification";
  provenance: "live" | "sample";
  message: string;
  disclaimer: "Signals, not guaranteed prediction.";
  subject: string | null;
  board: string | null;
  class_level?: string | null;
  repeated_topics: Array<{
    topic: string;
    chapter: string;
    count: number;
    years: number[];
    question_ids: string[];
  }>;
  question_type_distribution: Array<{ type: string; count: number; percentage: number }>;
  marks_distribution: Array<{ marks: number; count: number; percentage: number }>;
  chapter_priorities: Array<{
    chapter: string;
    total_questions: number;
    total_marks: number;
    topics: string[];
  }>;
  evidence: Array<{
    question_id: string;
    paper_id: string;
    source_id: string;
    paper_title: string;
    year: number | null;
    question_excerpt: string;
    marks: number | null;
    chapter: string;
    topic: string;
    source_url: string | null;
  }>;
  revision_plan: string[];
  data_coverage: { papers: number; questions: number; years: number[] };
};

function domainFromUrl(value: string) {
  try {
    return new URL(value).hostname.replace(/^www\./, "");
  } catch {
    return "";
  }
}

function yearFromText(value: string) {
  const match = value.match(/\b(19|20)\d{2}\b/);
  return match ? Number(match[0]) : null;
}

function buildLocalDiscoveryFallback(payload: PYQDiscoverySearchPayload): PYQDiscoverySearchResponse {
  const candidates = (payload.manual_urls ?? [])
    .map((url): PYQDiscoveryCandidate | null => {
      const sourceDomain = domainFromUrl(url);
      if (!sourceDomain) return null;
      const year = yearFromText(url) ?? payload.year_end ?? null;
      const officialSource = /(dhsekerala|scertkerala|keralapareekshabhavan|pareekshabhavan|kerala\.gov)\./i.test(sourceDomain);
      return {
        title: `${payload.subject || "Previous paper"} ${year ?? ""}`.trim(),
        url,
        snippet: "Public PYQ link supplied for review before import.",
        year,
        subject: payload.subject ?? null,
        board: payload.board ?? null,
        class_level: payload.class_level ?? null,
        source_domain: sourceDomain,
        source_title: sourceDomain,
        confidence_score: officialSource ? 0.82 : 0.55,
        official_source: officialSource,
        file_hash: null,
        notes: officialSource ? "Official/public source domain detected." : "Review this source before using it for analysis.",
        warnings: [],
      };
    })
    .filter((candidate): candidate is PYQDiscoveryCandidate => Boolean(candidate));

  return {
    enabled: false,
    provider: "disabled",
    configured: false,
    message: candidates.length
      ? "Review the public PYQ links below before importing them for analysis."
      : "Automatic PYQ discovery is not configured yet. Paste a public PYQ link, upload a paper, or broaden your search.",
    candidates,
  };
}

function buildLocalQuestionExtraction(paperId: string): PreviousQuestionExtractResponse {
  const questions = getLocalPreviousQuestions(paperId);
  return {
    previous_paper_id: paperId,
    model_used: "DocDoe local preview",
    question_count: questions.length,
    questions,
  };
}

export async function analyzePreviousPapers(payload: PyqAnalysisRequest) {
  return apiPost<PyqAnalysis, PyqAnalysisRequest>("/pyq/analyze", payload);
}

export function loadSamplePreviousPaperAnalysis(): PyqAnalysis {
  return {
    available: true,
    status: "available",
    provenance: "sample",
    message: "Example layout using clearly labelled sample evidence.",
    disclaimer: "Signals, not guaranteed prediction.",
    subject: "Biology",
    board: "Kerala HSE",
    class_level: "+2",
    repeated_topics: [{
      topic: "Cell division",
      chapter: "Cell Cycle",
      count: 2,
      years: [2022, 2023],
      question_ids: ["sample-q-1", "sample-q-2"],
    }],
    question_type_distribution: [
      { type: "short", count: 1, percentage: 50 },
      { type: "long", count: 1, percentage: 50 },
    ],
    marks_distribution: [
      { marks: 2, count: 1, percentage: 50 },
      { marks: 5, count: 1, percentage: 50 },
    ],
    chapter_priorities: [{
      chapter: "Cell Cycle",
      total_questions: 2,
      total_marks: 7,
      topics: ["Cell division"],
    }],
    evidence: [{
      question_id: "sample-q-1",
      paper_id: "sample-paper-2022",
      source_id: "sample-paper-2022",
      paper_title: "Sample Biology Paper 2022",
      year: 2022,
      question_excerpt: "Compare mitosis and meiosis.",
      marks: 5,
      chapter: "Cell Cycle",
      topic: "Cell division",
      source_url: null,
    }],
    revision_plan: ["Revise Cell Cycle, then practise one short and one long answer."],
    data_coverage: { papers: 2, questions: 2, years: [2022, 2023] },
  };
}

export async function listPreviousPapers() {
  if (shouldUseDemoData()) return delay(getLocalPreviousPapers());

  return withDemoFallback(
    () => apiGet<PreviousPaper[]>("/previous-papers"),
    () => delay(getLocalPreviousPapers()),
  );
}

export async function uploadPreviousPaper(input: PreviousPaperUploadInput) {
  if (shouldUseDemoData()) {
    const paper: LocalOfflinePreviousPaper = {
      id: `paper-local-${Date.now()}`,
      user_id: input.userId ?? demoUser.id,
      title: input.title || input.file.name.replace(/\.[^.]+$/, "") || "Uploaded previous paper",
      subject: input.subject || "Physics",
      syllabus: input.syllabus || "Indian Board Exams",
      year: input.year ?? new Date().getFullYear(),
      file_name: input.file.name,
      file_type: input.file.type || "PDF",
      file_path: "/demo/local-previous-paper",
      status: "ready",
      extracted_text: null,
      extraction_error: null,
      extracted_questions_json: [],
      created_at: new Date().toISOString(),
    };

    return delay(saveLocalPreviousPaper(paper));
  }

  const formData = new FormData();
  formData.append("file", input.file);
  if (input.title) formData.append("title", input.title);
  if (input.subject) formData.append("subject", input.subject);
  if (input.syllabus) formData.append("syllabus", input.syllabus);
  if (input.year) formData.append("year", String(input.year));

  return withDemoFallback(
    () => apiUpload<PreviousPaper>("/previous-papers/upload", formData, { timeoutMs: 60000 }),
    async () => {
      const paper: LocalOfflinePreviousPaper = {
        id: `paper-local-${Date.now()}`,
        user_id: input.userId ?? demoUser.id,
        title: input.title || input.file.name.replace(/\.[^.]+$/, "") || "Uploaded previous paper",
        subject: input.subject || "Study",
        syllabus: input.syllabus || "Indian Board Exams",
        year: input.year ?? new Date().getFullYear(),
        file_name: input.file.name,
        file_type: input.file.type || "PDF",
        file_path: "/demo/local-previous-paper",
        status: "ready",
        extracted_text: null,
        extraction_error: null,
        extracted_questions_json: [],
        created_at: new Date().toISOString(),
      };
      return saveLocalPreviousPaper(paper);
    },
  );
}

export async function listPreviousQuestions(paperId: string) {
  if (shouldUseDemoData(paperId)) {
    return delay(getLocalPreviousQuestions(paperId));
  }

  return withDemoFallback(
    () => apiGet<PreviousQuestion[]>(`/previous-papers/${paperId}/questions`),
    () => delay(getLocalPreviousQuestions(paperId)),
  );
}

export async function extractPreviousQuestions(
  paperId: string,
  payload: PreviousQuestionExtractRequest = {},
) {
  if (shouldUseDemoData(paperId)) {
    void payload;
    return delay(buildLocalQuestionExtraction(paperId));
  }

  return withDemoFallback(
    () => apiPost<PreviousQuestionExtractResponse, PreviousQuestionExtractRequest>(
      `/previous-papers/${paperId}/extract-questions`,
      payload,
    ),
    () => delay(buildLocalQuestionExtraction(paperId)),
  );
}

export async function analyzeStructuredPreviousPapers(
  payload: StructuredPreviousPaperAnalyzeRequest,
) {
  if (shouldUseDemoData()) {
    return delay(
      getLocalPreviousPaperAnalysis(
        payload.paper_ids ?? [],
        payload.subject,
        payload.syllabus,
      ),
    );
  }

  return withDemoFallback(
    () => apiPost<PreviousPaperAnalysisResponse, StructuredPreviousPaperAnalyzeRequest>(
      "/previous-papers/analyze-structured",
      payload,
    ),
    () => delay(
      getLocalPreviousPaperAnalysis(
        payload.paper_ids ?? [],
        payload.subject,
        payload.syllabus,
      ),
    ),
  );
}

export async function searchPYQDiscovery(payload: PYQDiscoverySearchPayload) {
  const fallback = buildLocalDiscoveryFallback(payload);

  return withDemoFallback(
    () => apiPost<PYQDiscoverySearchResponse, PYQDiscoverySearchPayload>(
      "/pyq-discovery/search",
      payload,
      { timeoutMs: 30000 },
    ),
    () => delay(fallback),
  );
}

export async function importPYQDiscoveryCandidate(candidate: PYQDiscoveryCandidate) {
  const fallback = () => {
    const paper: LocalOfflinePreviousPaper = {
      id: `paper-local-${Date.now()}`,
      user_id: demoUser.id,
      title: candidate.title || "Imported previous paper",
      subject: candidate.subject || "Physics",
      syllabus: candidate.board || "Indian Board Exams",
      year: candidate.year ?? new Date().getFullYear(),
      file_name: candidate.url.split("/").pop() || "previous-paper.pdf",
      file_type: "PDF",
      file_path: candidate.url,
      status: "ready",
      extracted_text: null,
      extraction_error: null,
      extracted_questions_json: [],
      created_at: new Date().toISOString(),
    };
    const saved = saveLocalPreviousPaper(paper);
    return {
      id: saved.id,
      title: saved.title,
      year: saved.year,
      subject: saved.subject,
      verification_status: "candidate",
      confidence_score: candidate.confidence_score,
      official_source: candidate.official_source,
      source_url: candidate.url,
      deduped: false,
    } satisfies PYQDiscoveryImportResponse;
  };

  if (shouldUseDemoData()) return delay(fallback());

  return withDemoFallback(
    () => apiPost<PYQDiscoveryImportResponse, PYQDiscoveryCandidate>(
      "/pyq-discovery/import",
      candidate,
      { timeoutMs: 30000 },
    ),
    () => delay(fallback()),
  );
}

// ─── Real Kerala previous-year papers (verified public archives) ──────────────

export type RealPyqPaper = {
  title: string;
  url: string;
  years?: number[];
  medium?: string;
  source: string;
};

export type RealPyqPapersResponse = {
  available: boolean;
  level: string;
  board: string;
  subject: string | null;
  papers: RealPyqPaper[];
  years_covered: number[];
  trust_note: string;
};

/** Fetch REAL downloadable Kerala previous-year question papers (not AI-generated). */
export async function getRealPyqPapers(params?: {
  subject?: string | null;
  classLevel?: string | null;
  board?: string | null;
}): Promise<RealPyqPapersResponse> {
  const q = new URLSearchParams();
  if (params?.subject) q.set("subject", params.subject);
  if (params?.classLevel) q.set("class_level", params.classLevel);
  if (params?.board) q.set("board", params.board);
  const suffix = q.toString() ? `?${q.toString()}` : "";
  return apiGet<RealPyqPapersResponse>(`/pyq/papers${suffix}`);
}