import { Router } from 'express';
import multer from 'multer';
import { foodRecordManager } from '../storage/database';
import { S3Storage } from 'coze-coding-dev-sdk';
import { LLMClient, Config } from 'coze-coding-dev-sdk';

const router = Router();

// 配置 multer 中间件
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 50 * 1024 * 1024 } // 限制 50MB
});

// 初始化对象存储
const storage = new S3Storage({
  endpointUrl: process.env.COZE_BUCKET_ENDPOINT_URL,
  accessKey: '',
  secretKey: '',
  bucketName: process.env.COZE_BUCKET_NAME,
  region: 'cn-beijing',
});

// 初始化大语言模型
const llmConfig = new Config();
const llmClient = new LLMClient(llmConfig);

// 获取食物记录列表
router.get('/', async (req, res) => {
  try {
    const { userId } = req.query;
    
    if (!userId || typeof userId !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'userId is required'
      });
    }

    const { mealType, startDate, endDate } = req.query;
    
    const records = await foodRecordManager.getFoodRecords({
      userId,
      mealType: mealType as string,
      startDate: startDate ? new Date(startDate as string) : undefined,
      endDate: endDate ? new Date(endDate as string) : undefined,
    });

    res.json({
      success: true,
      data: records
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 创建食物记录（手动添加）
router.post('/', async (req, res) => {
  try {
    const record = await foodRecordManager.createFoodRecord(req.body);
    
    res.json({
      success: true,
      data: record
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 删除食物记录
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const success = await foodRecordManager.deleteFoodRecord(id);
    
    res.json({
      success,
      message: success ? 'Record deleted successfully' : 'Record not found'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 拍照识别食物
router.post('/recognize', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: 'No image file provided'
      });
    }

    const { buffer, originalname, mimetype } = req.file;

    // 1. 上传图片到对象存储
    const imageKey = await storage.uploadFile({
      fileContent: buffer,
      fileName: `food-photos/${originalname}`,
      contentType: mimetype,
    });

    // 生成图片访问 URL
    const imageUrl = await storage.generatePresignedUrl({
      key: imageKey,
      expireTime: 86400 // 1天有效期
    });

    // 2. 调用大语言模型识别食物
    const base64Image = buffer.toString('base64');
    const dataUri = `data:${mimetype};base64,${base64Image}`;

    const messages = [
      {
        role: 'system' as const,
        content: '你是一个专业的食物营养分析助手。请分析图片中的食物，识别食物名称、估算重量，并计算热量。返回JSON格式，包含：foodName（食物名称）、weight（估算重量，单位克）、calories（估算热量，单位千卡）。'
      },
      {
        role: 'user' as const,
        content: [
          {
            type: 'text' as const,
            text: '请识别这张图片中的食物，并告诉我食物名称、估算重量和热量。'
          },
          {
            type: 'image_url' as const,
            image_url: {
              url: dataUri,
              detail: 'high' as const
            }
          }
        ]
      }
    ];

    const response = await llmClient.invoke(messages, {
      model: 'doubao-seed-1-6-vision-250815',
      temperature: 0.3
    });

    // 3. 解析AI返回的结果
    let foodInfo: any = {};
    try {
      // 尝试从响应中提取JSON
      const jsonMatch = response.content.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        foodInfo = JSON.parse(jsonMatch[0]);
      } else {
        // 如果没有返回JSON，使用默认值
        foodInfo = {
          foodName: '未知食物',
          weight: 100,
          calories: 100
        };
      }
    } catch (parseError) {
      // JSON解析失败，使用默认值
      foodInfo = {
        foodName: '未知食物',
        weight: 100,
        calories: 100
      };
    }

    // 4. 返回识别结果
    res.json({
      success: true,
      data: {
        foodName: foodInfo.foodName || '未知食物',
        weight: Number(foodInfo.weight) || 100,
        calories: Number(foodInfo.calories) || 100,
        imageUrl,
        imageKey,
        aiResponse: response.content
      }
    });

  } catch (error: any) {
    console.error('Food recognition error:', error);
    res.status(500).json({
      success: false,
      error: error.message || 'Failed to recognize food'
    });
  }
});

// 获取今日总热量
router.get('/total-calories', async (req, res) => {
  try {
    const { userId, date } = req.query;
    
    if (!userId || typeof userId !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'userId is required'
      });
    }

    const queryDate = date ? new Date(date as string) : new Date();
    const totalCalories = await foodRecordManager.getTotalCaloriesByDate(userId, queryDate);

    res.json({
      success: true,
      data: {
        date: queryDate.toISOString().split('T')[0],
        totalCalories
      }
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

export default router;
