import { NextRequest, NextResponse } from 'next/server';
import ZAI from 'z-ai-web-dev-sdk';

// ─── Types ──────────────────────────────────────────────────────────────────

interface OcrResult {
  phoneNumbers: string[];
  bkashNumbers: string[];
  nagadNumbers: string[];
  facebookProfiles: string[];
  amounts: string[];
  scamType: string;
  urgencyIndicators: string[];
  sellerName: string;
  description: string;
}

const emptyResult: OcrResult = {
  phoneNumbers: [],
  bkashNumbers: [],
  nagadNumbers: [],
  facebookProfiles: [],
  amounts: [],
  scamType: '',
  urgencyIndicators: [],
  sellerName: '',
  description: '',
};

// ─── System Prompt ──────────────────────────────────────────────────────────

const OCR_SYSTEM_PROMPT = `You are an OCR assistant specialized in extracting scam-related information from screenshots of messages, chats, and social media posts targeting people in Bangladesh.

Analyze the image carefully and extract any of the following information that is visible:

1. **phoneNumbers**: Any phone numbers (Bangladeshi format: +880, 01XXXXXXXXX, etc.)
2. **bkashNumbers**: Any bKash numbers (usually start with 01, 11 digits)
3. **nagadNumbers**: Any Nagad numbers (usually start with 01, 11 digits)
4. **facebookProfiles**: Any Facebook profile/page URLs or names
5. **amounts**: Any monetary amounts mentioned (in BDT/৳/Tk/Rs)
6. **scamType**: What type of scam this appears to be (e.g., "online-shopping", "mobile-banking", "phishing", "job-scam", "investment", "lottery", "impersonation", etc.)
7. **urgencyIndicators**: Any urgency language detected (e.g., "hurry", "limited time", "act now", "urgent")
8. **sellerName**: Any name of a seller, shop, or organization mentioned
9. **description**: A brief description of what the screenshot shows (2-3 sentences)

Return your analysis as a JSON object with this exact structure:
{
  "phoneNumbers": ["string", ...],
  "bkashNumbers": ["string", ...],
  "nagadNumbers": ["string", ...],
  "facebookProfiles": ["string", ...],
  "amounts": ["string", ...],
  "scamType": "string",
  "urgencyIndicators": ["string", ...],
  "sellerName": "string",
  "description": "string"
}

Rules:
- Extract ONLY information that is clearly visible in the image
- For phone numbers, use the format as displayed (don't add country code if not shown)
- For amounts, include the currency symbol if visible
- If a field has no data, use an empty array or empty string as appropriate
- Respond ONLY with the JSON object, no additional text
- Be accurate - do not hallucinate information that is not in the image`;

// ─── POST Handler ───────────────────────────────────────────────────────────

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { image } = body;

    if (!image || typeof image !== 'string') {
      return NextResponse.json(
        { success: false, error: 'Base64 image is required' },
        { status: 400 }
      );
    }

    // Validate base64 image format
    const base64Regex = /^data:image\/(png|jpeg|jpg|webp);base64,/i;
    if (!base64Regex.test(image) && !/^[A-Za-z0-9+/]+=*$/.test(image)) {
      return NextResponse.json(
        { success: false, error: 'Invalid base64 image format' },
        { status: 400 }
      );
    }

    let ocrResult: OcrResult;

    try {
      // Use VLM to analyze the image
      const zai = await ZAI.create();
      const response = await zai.chat.completions.create({
        messages: [
          { role: 'system', content: OCR_SYSTEM_PROMPT },
          {
            role: 'user',
            content: [
              {
                type: 'image_url',
                image_url: {
                  url: image.startsWith('data:') ? image : `data:image/png;base64,${image}`,
                },
              },
              {
                type: 'text',
                text: 'Please analyze this screenshot and extract any scam-related information visible in it.',
              },
            ],
          },
        ],
        thinking: { type: 'disabled' },
      });

      const content = response.choices[0]?.message?.content;

      if (!content) {
        throw new Error('Empty response from VLM');
      }

      // Try to extract JSON from the response
      let jsonStr = content.trim();

      // Remove markdown code block wrappers if present
      const codeBlockMatch = jsonStr.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
      if (codeBlockMatch) {
        jsonStr = codeBlockMatch[1].trim();
      }

      const parsed = JSON.parse(jsonStr);

      // Validate and normalize the result
      ocrResult = {
        phoneNumbers: Array.isArray(parsed.phoneNumbers)
          ? parsed.phoneNumbers.filter((n: unknown) => typeof n === 'string')
          : [],
        bkashNumbers: Array.isArray(parsed.bkashNumbers)
          ? parsed.bkashNumbers.filter((n: unknown) => typeof n === 'string')
          : [],
        nagadNumbers: Array.isArray(parsed.nagadNumbers)
          ? parsed.nagadNumbers.filter((n: unknown) => typeof n === 'string')
          : [],
        facebookProfiles: Array.isArray(parsed.facebookProfiles)
          ? parsed.facebookProfiles.filter((n: unknown) => typeof n === 'string')
          : [],
        amounts: Array.isArray(parsed.amounts)
          ? parsed.amounts.filter((n: unknown) => typeof n === 'string')
          : [],
        scamType: typeof parsed.scamType === 'string' ? parsed.scamType : '',
        urgencyIndicators: Array.isArray(parsed.urgencyIndicators)
          ? parsed.urgencyIndicators.filter((n: unknown) => typeof n === 'string')
          : [],
        sellerName: typeof parsed.sellerName === 'string' ? parsed.sellerName : '',
        description: typeof parsed.description === 'string' ? parsed.description : '',
      };
    } catch (vlmError) {
      console.warn('VLM OCR analysis failed:', vlmError);
      // Return empty result with a note that OCR failed
      ocrResult = {
        ...emptyResult,
        description: 'Could not analyze the image. Please enter the information manually.',
      };
    }

    return NextResponse.json(
      { success: true, data: ocrResult },
      { status: 200 }
    );
  } catch (error) {
    console.error('OCR analyze error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
