# Task 6 - Build PDF Upload & VLM-based MCQ Extraction API

## Agent: full-stack-developer

## Summary
Created the `/api/admin/mcq/extract-pdf` POST endpoint that accepts PDF uploads, converts pages to images, and uses VLM (Vision Language Model) to extract MCQ questions.

## Files Created/Modified
- **Created**: `/src/app/api/admin/mcq/extract-pdf/route.ts` - Main API route
- **Modified**: `/home/z/my-project/worklog.md` - Appended work record

## Packages Installed
- `pdf-img-convert@2.0.0` - Pure JS PDF-to-image conversion (no system dependencies like poppler)

## Implementation Details

### API Endpoint: POST `/api/admin/mcq/extract-pdf`

**Input**: multipart/form-data
- `file` (required): PDF file (max 20MB)
- `classId` (optional): Auto-assign to extracted MCQs
- `subjectId` (optional): Auto-assign to extracted MCQs
- `topicId` (optional): Auto-assign to extracted MCQs

**Process Flow**:
1. Auth check via `verifyAdminPermission(request, 'canManageMCQ')`
2. Rate limit: 5 requests/minute (strict due to VLM cost)
3. Validate file type (PDF), size (≤20MB), and optional DB references
4. Convert PDF to page images using `pdf-img-convert` (max 30 pages, 1200×1600 resolution)
5. For each page, send base64 image to VLM (ZAI SDK, `glm-4v-flash` model) with MCQ extraction prompt
6. Parse VLM JSON response with resilient parser (handles markdown fences, validates fields)
7. Continue on per-page errors (graceful degradation)
8. Return structured response with all extracted questions

**Output Format**:
```json
{
  "success": true,
  "extractedQuestions": [
    {
      "question": "...",
      "optionA": "...",
      "optionB": "...",
      "optionC": "...",
      "optionD": "...",
      "correctAnswer": "A",
      "explanation": "...",
      "difficulty": "medium",
      "hasImage": false,
      "classId": "...",
      "subjectId": "...",
      "topicId": "..."
    }
  ],
  "totalExtracted": 25,
  "pagesProcessed": 5,
  "errors": ["Page 3: VLM returned empty response"],
  "message": "Extracted 25 MCQs from 5 page(s)"
}
```

### VLM Prompt Design
- Instructs extraction of ALL MCQs from page image
- Supports Bangla, English, Math, and Science
- Returns strict JSON format (no markdown fences)
- Flags questions with images/diagrams via `hasImage`
- Infers difficulty from question complexity
- Handles answer keys visible on the page

### Error Handling
- Invalid file type → 400
- File too large → 400
- Invalid classId/subjectId/topicId → 400
- PDF conversion failure → 422
- Per-page VLM failures → logged, other pages continue
- Unhandled errors → 500

## Lint Status
✅ Passes cleanly with no errors
