import path from 'path';
import fs from 'fs';

const DATA_DIR = process.env.DATA_DIR || path.join(process.cwd(), 'data');
const SHARE_DIR = path.join(DATA_DIR, 'sharepage');

const IMAGE_NOTE_MARKER = '\n\n[Images provided at the following paths:]';
const IMAGE_NOTE_MARKER_ALT = '[Images provided at the following paths:]';

/**
 * 去除用户消息文本中由 handleImages 追加的图片路径注释
 */
export function stripImagePaths(text) {
  if (!text) return text;
  const idx = text.indexOf(IMAGE_NOTE_MARKER);
  if (idx !== -1) return text.slice(0, idx);
  if (text.startsWith(IMAGE_NOTE_MARKER_ALT)) return '';
  return text;
}

const SKIP_USER_PREFIXES = [
  '<command-args>',
  '<local-command-stdout>',
  '<system-reminder>',
  '[Background Task Result]',
  '<task-notification>',
  'Caveat:',
  'This session is being continued from a previous',
  '[Request interrupted',
];

/**
 * 从包含 <command-message> 标签的文本中提取命令消息内容
 * e.g. "<command-message>foo</command-message><command-name>/foo</command-name>" → "foo"
 */
function extractCommandMessage(text) {
  const m = text.match(/<command-message>([\s\S]*?)<\/command-message>/);
  return m ? m[1].trim() : null;
}

/**
 * 从原始 JSONL 消息数组中提取纯文本消息（过滤工具调用、系统消息等）
 * @param {Array} rawMessages
 * @returns {Array<{role, content, timestamp, uuid}>}
 */
export function extractShareMessages(rawMessages) {
  const results = [];

  for (const msg of rawMessages) {
    if (msg.isMeta) continue;

    const role = msg.message?.role;
    if (role !== 'user' && role !== 'assistant') continue;

    const content = msg.message?.content;

    if (role === 'user') {
      let text = '';
      if (typeof content === 'string') {
        text = content;
      } else if (Array.isArray(content)) {
        text = content.filter(p => p.type === 'text').map(p => p.text).join('\n');
      }
      if (!text) continue;
      if (SKIP_USER_PREFIXES.some(prefix => text.startsWith(prefix))) continue;
      if (text.startsWith('<command-message>') || text.startsWith('<command-name>')) {
        const cmd = extractCommandMessage(text);
        if (!cmd) continue;
        text = `/${cmd}`;
      } else {
        text = stripImagePaths(text);
        if (!text) continue;
      }

      results.push({ role: 'user', content: text, timestamp: msg.timestamp, uuid: msg.uuid });

    } else if (role === 'assistant') {
      let text = '';
      if (typeof content === 'string') {
        text = content;
      } else if (Array.isArray(content)) {
        text = content.filter(p => p.type === 'text').map(p => p.text).join('\n');
      }
      if (!text.trim()) continue;

      results.push({ role: 'assistant', content: text, timestamp: msg.timestamp, uuid: msg.uuid });
    }
  }

  return results;
}

/**
 * 保存静态快照 JSON（供前端渲染）
 * @returns {string} JSON 文件绝对路径
 */
export function saveStaticSnapshot(messages, userUuid, sessionId, title) {
  const sessionDir = path.join(SHARE_DIR, userUuid, sessionId);
  fs.mkdirSync(sessionDir, { recursive: true });

  const jsonPath = path.join(sessionDir, 'snapshot.json');
  fs.writeFileSync(jsonPath, JSON.stringify({
    messages,
    title,
    generatedAt: new Date().toISOString(),
  }, null, 2), 'utf8');

  return jsonPath;
}

/**
 * 读取静态快照 JSON
 * @returns {{ messages, title, generatedAt } | null}
 */
export function readStaticSnapshot(userUuid, sessionId) {
  const jsonPath = path.join(SHARE_DIR, userUuid, sessionId, 'snapshot.json');
  try {
    return JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
  } catch {
    return null;
  }
}
