const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { authMiddleware } = require('../middleware/auth');
const { parseTicketImage, getOCRResult } = require('../services/ocr');
const { ocrLimiter } = require('../middleware/rateLimiter');
const logger = require('../services/logger');

const router = express.Router();

// 配置文件上传
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只支持图片文件'));
    }
  }
});

router.use(authMiddleware);

// 上传并解析彩票图片 (改为异步)
router.post('/parse', ocrLimiter, upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: '请上传图片' });
  }

  try {
    const { taskId } = parseTicketImage(req.file.path);
    logger.info(`OCR任务已提交: ${taskId}`);
    res.json({ taskId, status: 'processing', message: '图片已提交处理，请稍后查询结果' });
  } catch (err) {
    logger.error('OCR提交失败', { error: err.message });
    res.status(500).json({ error: err.message || '提交失败' });
  }
});

// 查询OCR结果
router.get('/result/:taskId', (req, res) => {
  const { taskId } = req.params;

  if (!taskId || !taskId.startsWith('ocr_')) {
    return res.status(400).json({ error: '无效的任务ID' });
  }

  try {
    const result = getOCRResult(taskId);

    if (result.completed) {
      if (result.success) {
        res.json({
          status: 'completed',
          ...result.data
          // image_path 在提交时由客户端记录，此处无需返回
        });
      } else {
        res.status(500).json({ status: 'failed', error: result.error });
      }
    } else {
      res.json({ status: result.processing ? 'processing' : 'pending', taskId });
    }
  } catch (err) {
    logger.error('OCR结果查询失败', { taskId, error: err.message });
    res.status(500).json({ error: '查询失败' });
  }
});

module.exports = router;
