'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');

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 formatLocalISO(d) {
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

function todoTool(args) {
  const { action, content, id, remind_at, keywords } = args;

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

  // 校验 remind_at（如果提供）
  if (remind_at !== undefined && remind_at !== null) {
    if (action !== 'add' && action !== 'update') {
      return { success: false, error: `remind_at 仅在 add 和 update 时有效` };
    }
    const ts = new Date(remind_at).getTime();
    if (isNaN(ts)) {
      return { success: false, error: 'remind_at 必须是有效的 ISO 8601 时间字符串，例如 2026-05-01T14:45:00' };
    }
  }

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

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

  // --- complete / delete / update (都需要 id) ---
  if (!id) {
    return { success: false, error: `${action} 需要提供 id，请从 recall 工具的搜索结果中获取` };
  }

  const idx = memories.findIndex(m => m.id === id && m.type === 'todo');
  if (idx === -1) {
    return { success: false, error: `未找到 id=${id} 的待办` };
  }

  // --- complete ---
  if (action === 'complete') {
    memories[idx].completed = true;
    memories[idx].completed_at = now;
    // 已完成的不再提醒
    delete memories[idx].remind_at;
    delete memories[idx].reminded;
    memories[idx].updated_at = now;
    saveMemories(memories);
    return {
      success: true,
      action: 'complete',
      entry: memories[idx],
      total: memories.length,
    };
  }

  // --- delete ---
  if (action === 'delete') {
    const removed = memories.splice(idx, 1)[0];
    saveMemories(memories);
    return {
      success: true,
      action: 'delete',
      entry: removed,
      total: memories.length,
    };
  }

  // --- update ---
  if (action === 'update') {
    if (content !== undefined && content !== null) {
      memories[idx].content = String(content).trim();
    }
    if (keywords !== undefined) {
      memories[idx].keywords = Array.isArray(keywords) ? keywords.filter(k => k && typeof k === 'string') : [];
    }
    // 更新提醒时间
    if (remind_at !== undefined) {
      if (remind_at === null) {
        delete memories[idx].remind_at;
        delete memories[idx].reminded;
      } else {
        memories[idx].remind_at = formatLocalISO(new Date(remind_at));
        memories[idx].reminded = false;
      }
    }
    memories[idx].updated_at = now;
    saveMemories(memories);
    return {
      success: true,
      action: 'update',
      entry: memories[idx],
      total: memories.length,
    };
  }

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

module.exports = { todoTool };
