import { NextRequest, NextResponse } from "next/server"

const OCR_SERVICE_URL = "http://192.168.10.236:8000/ocr/predict-pdf-file"

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get("file")

    if (!file || !(file instanceof Blob)) {
      return NextResponse.json({ error: "请上传文件" }, { status: 400 })
    }

    const ocrFormData = new FormData()
    const fileName = file instanceof File ? file.name : "file"
    ocrFormData.append("file", file, fileName)

    const response = await fetch(OCR_SERVICE_URL, {
      method: "POST",
      body: ocrFormData,
      signal: AbortSignal.timeout(60000),
    })

    if (!response.ok) {
      return NextResponse.json(
        { error: `OCR 服务请求失败 (${response.status})` },
        { status: 502 }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error("OCR API error:", error)
    return NextResponse.json(
      { error: "OCR 识别失败，请稍后重试" },
      { status: 500 }
    )
  }
}

export const config = {
  api: {
    bodyParser: false,
  },
}
