import express from 'express';
import fs from 'fs';
import { shareDb, userDb, imageDb } from '../database/db.js';
import { getImagePath } from '../services/image-storage.js';
import { getSessionMessages, loadProjectConfig } from '../projects.js';
import { extractShareMessages, saveStaticSnapshot, readStaticSnapshot, stripImagePaths } from '../services/share-renderer.js';
import { authenticateToken } from '../middleware/auth.js';

const router = express.Router();

/**
 * 将 imageDb.getImagesBySession 的结果附加到提取后的消息上。
 * message_images 表中 message_content 存储的是原始用户文本（未追加图片路径）；
 * 提取后的 msg.content 已经过 stripImagePaths 清洗，两者可直接比较。
 */
function attachImagesToMessages(messages, sessionImages) {
  if (!sessionImages || sessionImages.length === 0) return;

  // 按 message_content 分组（可能有多张图片属于同一条消息）
  const contentMap = new Map(); // message_content -> [{id, name}]
  for (const img of sessionImages) {
    const key = img.message_content || '';
    if (!contentMap.has(key)) contentMap.set(key, []);
    contentMap.get(key).push({ id: img.id, name: img.original_name });
  }

  const usedKeys = new Set();
  for (const msg of messages) {
    if (msg.role !== 'user') continue;
    const content = msg.content || '';
    for (const [mcKey, images] of contentMap) {
      if (usedKeys.has(mcKey)) continue;
      // mcKey 是原始文本（最多 500 字符），content 是完整原始文本（已清洗）
      const matched = mcKey.length > 0
        ? content.startsWith(mcKey) || mcKey.startsWith(content.substring(0, 500))
        : content.length === 0;
      if (matched) {
        msg.images = images;
        usedKeys.add(mcKey);
        break;
      }
    }
  }
}

// GET /api/share/info/:sessionId — 获取当前用户的分享状态（需要鉴权，必须在 /:userUuid/:sessionId 前定义）
router.get('/info/:sessionId', authenticateToken, (req, res) => {
  const { sessionId } = req.params;
  const userUuid = req.user.uuid;

  const share = shareDb.getShare(userUuid, sessionId);
  if (!share) {
    return res.status(404).json({ error: 'not found' });
  }
  res.json({
    mode: share.share_mode,
    status: share.status,
    shareUrl: `/share/${userUuid}/${sessionId}`,
  });
});

// GET /api/share/:userUuid/:sessionId — 公开访问，返回分享数据
router.get('/:userUuid/:sessionId', async (req, res) => {
  const { userUuid, sessionId } = req.params;

  const share = shareDb.getShare(userUuid, sessionId);
  if (!share || share.status !== 'active') {
    return res.status(404).json({ error: '分享不存在或已关闭' });
  }

  const user = userDb.getUserByUuid(userUuid);
  const sharerName = user?.email || user?.username || '';

  const projectConfig = await loadProjectConfig(userUuid);
  const projectDisplayName = projectConfig[share.project_name]?.displayName || share.project_name;

  if (share.share_mode === 'realtime') {
    try {
      const rawMessages = await getSessionMessages(share.project_name, sessionId, null, 0, userUuid);
      const messages = extractShareMessages(rawMessages);
      const sessionImages = imageDb.getImagesBySession(sessionId);
      attachImagesToMessages(messages, sessionImages);
      return res.json({
        mode: 'realtime',
        title: share.session_title || '对话分享',
        projectName: projectDisplayName,
        messages,
        sharerName,
      });
    } catch (err) {
      console.error('[share] Failed to read realtime messages:', err);
      return res.status(500).json({ error: '读取消息失败' });
    }
  }

  // 静态模式：读取 snapshot.json
  const snapshot = readStaticSnapshot(userUuid, sessionId);
  if (!snapshot) {
    return res.status(500).json({ error: '读取快照失败' });
  }
  const messages = snapshot.messages || [];
  const sessionImages = imageDb.getImagesBySession(sessionId);
  attachImagesToMessages(messages, sessionImages);
  return res.json({
    mode: 'static',
    title: share.session_title || snapshot.title || '对话分享',
    projectName: projectDisplayName,
    messages,
    generatedAt: snapshot.generatedAt,
    sharerName,
  });
});

// POST /api/share — 创建或更新分享（需要鉴权）
router.post('/', authenticateToken, async (req, res) => {
  const { sessionId, projectName, mode, title } = req.body;
  const userUuid = req.user.uuid;

  if (!sessionId || !projectName || !mode) {
    return res.status(400).json({ error: '缺少必要参数' });
  }
  if (mode !== 'realtime' && mode !== 'static') {
    return res.status(400).json({ error: '无效的分享模式' });
  }

  if (mode === 'static') {
    try {
      const rawMessages = await getSessionMessages(projectName, sessionId, null, 0, userUuid);
      const messages = extractShareMessages(rawMessages);
      saveStaticSnapshot(messages, userUuid, sessionId, title);
    } catch (err) {
      console.error('[share] Failed to save static snapshot:', err);
      return res.status(500).json({ error: '保存快照失败' });
    }
  }

  shareDb.upsertShare({
    userUuid,
    sessionId,
    projectName,
    shareMode: mode,
    sessionTitle: title || null,
  });

  const shareUrl = `/share/${userUuid}/${sessionId}`;
  res.json({ shareUrl, mode });
});

// DELETE /api/share/:sessionId — 停止分享（需要鉴权）
router.delete('/:sessionId', authenticateToken, (req, res) => {
  const { sessionId } = req.params;
  const userUuid = req.user.uuid;

  shareDb.stopShare(userUuid, sessionId);
  res.json({ ok: true });
});

// GET /api/share/:userUuid/:sessionId/images/:imageId — 公开访问，分享页图片
router.get('/:userUuid/:sessionId/images/:imageId', (req, res) => {
  const { userUuid, sessionId, imageId } = req.params;

  const share = shareDb.getShare(userUuid, sessionId);
  if (!share || share.status !== 'active') {
    return res.status(404).json({ error: '分享不存在或已关闭' });
  }

  const imgId = parseInt(imageId, 10);
  if (isNaN(imgId)) return res.status(400).json({ error: 'Invalid image ID' });

  const image = imageDb.getImageById(imgId);
  if (!image || image.user_uuid !== userUuid) {
    return res.status(404).json({ error: 'Image not found' });
  }

  const filePath = getImagePath(image.user_uuid, image.file_hash, image.file_ext);
  if (!fs.existsSync(filePath)) {
    return res.status(410).json({ error: 'Image expired' });
  }

  res.setHeader('Content-Type', image.mime_type);
  res.setHeader('Cache-Control', 'public, max-age=3600');
  res.sendFile(filePath);
});

export default router;
