'use strict';
// Persistent activity log for coding sessions, tasks, and skills.
// Events persist in brain DB so users can see "what happened while I was away."

let brain;
function getBrain() { if (!brain) brain = require('../brain'); return brain; }

/**
 * Log an activity entry.
 * @param {Object} entry
 * @param {string} [entry.session_id] - Associated session/task ID
 * @param {string} entry.type - Event type (coding_start, coding_complete, coding_error, task_complete, task_error, etc.)
 * @param {string} entry.title - Human-readable title
 * @param {string} [entry.body] - Short description / first N chars of output
 * @param {string} [entry.detail] - JSON metadata blob
 */
function log(entry) {
  const db = getBrain().getDb();
  db.prepare(
    `INSERT INTO activity_log (session_id, type, title, body, detail)
     VALUES (?, ?, ?, ?, ?)`
  ).run(
    entry.session_id || null,
    entry.type,
    entry.title,
    entry.body || null,
    entry.detail || null,
  );
}

/**
 * List activity entries with optional filters.
 * @param {Object} [opts]
 * @param {number} [opts.limit=50]
 * @param {number} [opts.offset=0]
 * @param {string} [opts.type] - Filter by type
 * @param {boolean} [opts.unreadOnly] - Only unread entries
 * @returns {Array}
 */
function list({ limit = 50, offset = 0, type, unreadOnly } = {}) {
  const db = getBrain().getDb();
  const conditions = [];
  const params = [];

  if (type) {
    conditions.push('type = ?');
    params.push(type);
  }
  if (unreadOnly) {
    conditions.push('read = 0');
  }

  const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
  params.push(limit, offset);

  return db.prepare(
    `SELECT * FROM activity_log ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`
  ).all(...params);
}

/**
 * Mark a single activity entry as read.
 * @param {number} id
 */
function markRead(id) {
  const db = getBrain().getDb();
  db.prepare('UPDATE activity_log SET read = 1 WHERE id = ?').run(id);
}

/**
 * Mark all unread entries as read.
 */
function markAllRead() {
  const db = getBrain().getDb();
  db.prepare('UPDATE activity_log SET read = 1 WHERE read = 0').run();
}

/**
 * Get the count of unread activity entries.
 * @returns {number}
 */
function unreadCount() {
  const db = getBrain().getDb();
  const row = db.prepare('SELECT count(*) AS cnt FROM activity_log WHERE read = 0').get();
  return row.cnt;
}

/**
 * Delete activity entries older than N days.
 * @param {number} [days=30]
 */
function cleanup(days = 30) {
  const db = getBrain().getDb();
  db.prepare(
    `DELETE FROM activity_log WHERE created_at < datetime('now', '-' || ? || ' days')`
  ).run(days);
}

module.exports = { log, list, markRead, markAllRead, unreadCount, cleanup };
