import { getDb, nowIso, newId } from './db.js';
const SCOPES = new Set(['agent', 'project', 'global']);
function row(r, engine){
  if (!r) return null;
  const out = { ...r, local_only: r.local_only === 1 };
  if (out.local_only && engine !== 'ollama') { out.content = '[local-only memory redacted]'; out.redacted = true; } else { out.redacted = false; }
  return out;
}
export function addMemory(input = {}) {
  if (!SCOPES.has(input.scope)) throw new Error('invalid memory scope');
  if (!input.content) throw new Error('content is required');
  const now = nowIso(); const id = newId('mem');
  getDb().prepare(`INSERT INTO agent_memory (id, agent_id, project_id, scope, kind, content, source, local_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
    .run(id, input.agent_id || null, input.project_id || null, input.scope, input.kind || 'note', String(input.content), input.source || null, input.local_only ? 1 : 0, now, now);
  return getDb().prepare('SELECT * FROM agent_memory WHERE id = ?').get(id);
}
export function listMemory(opts = {}) {
  const where=[]; const params=[];
  if (opts.agent_id) { where.push('(agent_id = ? OR scope != ?)'); params.push(opts.agent_id, 'agent'); }
  if (opts.project_id) { where.push('(project_id = ? OR scope = ?)'); params.push(opts.project_id, 'global'); }
  const sql = `SELECT * FROM agent_memory ${where.length ? 'WHERE '+where.join(' AND ') : ''} ORDER BY updated_at DESC`;
  return getDb().prepare(sql).all(...params).map(r => row(r, opts.engine || 'ollama'));
}
export function recallForAgent(agentId, projectId, query = '', engine) {
  if (!engine) throw new Error('engine parameter required');
  const tokens = String(query || '').toLowerCase().split(/\s+/).filter(Boolean).slice(0, 8);
  const visible = `(scope = 'global' OR (scope = 'project' AND project_id = ?) OR (scope = 'agent' AND agent_id = ?))`;
  const params = [projectId || '', agentId || ''];
  let sql = `SELECT * FROM agent_memory WHERE ${visible}`;
  if (tokens.length) {
    sql += ` AND (${tokens.map(() => 'LOWER(content) LIKE ?').join(' OR ')})`;
    params.push(...tokens.map(t => `%${t}%`));
  }
  sql += ' ORDER BY updated_at DESC LIMIT 50';
  const rows = getDb().prepare(sql).all(...params);
  return rows.map(r => row(r, engine));
}
export function deleteMemory(id) { getDb().prepare('DELETE FROM agent_memory WHERE id = ?').run(id); return true; }
