'use strict';

const fs = require('fs');
const path = require('path');
const os = require('os');

const MEMORY_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'VoiceInput', 'memory');
const MEMORY_FILE = path.join(MEMORY_DIR, 'memory.json');

function loadMemories() {
  if (!fs.existsSync(MEMORY_FILE)) {
    return [];
  }
  try {
    const raw = fs.readFileSync(MEMORY_FILE, 'utf8');
    return JSON.parse(raw);
  } catch (_) {
    return [];
  }
}

function recallTool(args) {
  const {
    types,
    query,
    start_date,
    end_date,
    max_results = 10,
  } = args;

  let memories = loadMemories();

  // 按类型过滤
  if (Array.isArray(types) && types.length > 0) {
    memories = memories.filter(m => types.includes(m.type));
  }

  // 按时间区间过滤
  if (start_date) {
    const start = new Date(start_date).getTime();
    if (!isNaN(start)) {
      memories = memories.filter(m => new Date(m.created_at).getTime() >= start);
    }
  }
  if (end_date) {
    const end = new Date(end_date).getTime();
    if (!isNaN(end)) {
      memories = memories.filter(m => new Date(m.created_at).getTime() <= end);
    }
  }

  // 按关键词搜索（在 content 和 keywords 中匹配）
  if (query && query.trim()) {
    const q = query.trim().toLowerCase();
    memories = memories.filter(m => {
      // 匹配内容
      if ((m.content || '').toLowerCase().includes(q)) return true;
      // 匹配关键词
      if (Array.isArray(m.keywords)) {
        return m.keywords.some(kw => (kw || '').toLowerCase().includes(q));
      }
      return false;
    });
  }

  // 按更新时间倒序排列
  memories.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());

  // 限制返回数量
  const total = memories.length;
  if (max_results > 0 && memories.length > max_results) {
    memories = memories.slice(0, max_results);
  }

  return {
    success: true,
    query: query || null,
    types: types || null,
    total,
    returned: memories.length,
    results: memories,
  };
}

module.exports = { recallTool };
