'use strict';

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

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

const VALID_TYPES = ['preference', 'habit', 'event', 'todo', 'identity', 'relationship', 'other'];

function ensureDir() {
  if (!fs.existsSync(MEMORY_DIR)) {
    fs.mkdirSync(MEMORY_DIR, { recursive: true });
  }
}

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

function saveMemories(memories) {
  ensureDir();
  fs.writeFileSync(MEMORY_FILE, JSON.stringify(memories, null, 2), 'utf8');
}

function generateId() {
  return crypto.randomUUID().slice(0, 8);
}

function rememberTool(args) {
  const { action, type, content, keywords, id } = args;

  // 校验 action
  if (!['add', 'update', 'delete'].includes(action)) {
    return { success: false, error: 'action 必须是 add / update / delete' };
  }

  // 校验 type
  if (action !== 'delete' && !VALID_TYPES.includes(type)) {
    return { success: false, error: `type 必须为: ${VALID_TYPES.join(', ')}` };
  }

  const memories = loadMemories();
  const now = new Date().toISOString();

  if (action === 'add') {
    if (!content || !content.trim()) {
      return { success: false, error: 'content 不能为空' };
    }
    const entry = {
      id: generateId(),
      type,
      content: content.trim(),
      keywords: Array.isArray(keywords) ? keywords.filter(k => k && typeof k === 'string') : [],
      created_at: now,
      updated_at: now,
    };
    memories.push(entry);
    saveMemories(memories);
    return {
      success: true,
      action: 'add',
      entry,
      total: memories.length,
    };
  }

  if (action === 'update') {
    if (!id) {
      return { success: false, error: 'update 需要提供 id' };
    }
    const idx = memories.findIndex(m => m.id === id);
    if (idx === -1) {
      return { success: false, error: `未找到 id=${id} 的记忆` };
    }
    if (content !== undefined && content !== null) {
      memories[idx].content = String(content).trim();
    }
    if (type !== undefined) {
      memories[idx].type = type;
    }
    if (keywords !== undefined) {
      memories[idx].keywords = Array.isArray(keywords) ? keywords.filter(k => k && typeof k === 'string') : [];
    }
    memories[idx].updated_at = now;
    saveMemories(memories);
    return {
      success: true,
      action: 'update',
      entry: memories[idx],
      total: memories.length,
    };
  }

  if (action === 'delete') {
    if (!id) {
      return { success: false, error: 'delete 需要提供 id' };
    }
    const idx = memories.findIndex(m => m.id === id);
    if (idx === -1) {
      return { success: false, error: `未找到 id=${id} 的记忆` };
    }
    const removed = memories.splice(idx, 1)[0];
    saveMemories(memories);
    return {
      success: true,
      action: 'delete',
      entry: removed,
      total: memories.length,
    };
  }

  return { success: false, error: '未知 action' };
}

module.exports = { rememberTool };
