import { getDatabase } from '../database/init.js';
import { deleteMemory } from './store.js';
import { backupMemoriesDb } from './backup.js';
const DEFAULTS = {
    salienceLte: 0.2,
    ageDaysGte: 30,
    excludePinned: true,
    dryRun: true,
};
const SAMPLE_LIMIT = 10;
function buildWhereClause(options) {
    const where = [
        'salience <= ?',
        "(julianday('now') - julianday(created_at)) >= ?",
        "COALESCE(status, 'active') NOT IN ('archived', 'suppressed')",
    ];
    const params = [options.salienceLte, options.ageDaysGte];
    if (options.project !== null) {
        where.push('project = ?');
        params.push(options.project);
    }
    if (options.excludePinned) {
        where.push('COALESCE(pinned, 0) = 0');
    }
    return { where: where.join(' AND '), params };
}
/**
 * Find + optionally delete memories below a salience threshold older than N
 * days. Always backs up the live DB before any delete; the backup path is
 * returned in the result so the caller can surface it to the user.
 */
export async function pruneMemories(rawOptions = {}) {
    const options = {
        salienceLte: rawOptions.salienceLte ?? DEFAULTS.salienceLte,
        ageDaysGte: rawOptions.ageDaysGte ?? DEFAULTS.ageDaysGte,
        project: rawOptions.project ?? null,
        excludePinned: rawOptions.excludePinned ?? DEFAULTS.excludePinned,
        dryRun: rawOptions.dryRun ?? DEFAULTS.dryRun,
    };
    if (options.salienceLte < 0 || options.salienceLte > 1) {
        throw new Error('salienceLte must be between 0 and 1');
    }
    if (options.ageDaysGte < 0) {
        throw new Error('ageDaysGte must be >= 0');
    }
    const { where, params } = buildWhereClause(options);
    const db = getDatabase();
    const countRow = db.prepare(`SELECT COUNT(*) AS n FROM memories WHERE ${where}`).get(...params);
    const matched = countRow.n;
    const sampleRows = db
        .prepare(`SELECT id, title, project, salience,
              CAST(julianday('now') - julianday(created_at) AS INTEGER) AS age_days
       FROM memories WHERE ${where}
       ORDER BY salience ASC, created_at ASC
       LIMIT ?`)
        .all(...params, SAMPLE_LIMIT);
    const sample = sampleRows.map((r) => ({
        id: r.id,
        title: r.title,
        project: r.project,
        salience: r.salience,
        ageDays: r.age_days,
    }));
    const result = { options, matched, sample };
    if (options.dryRun || matched === 0)
        return result;
    result.backupPath = await backupMemoriesDb('pre-prune');
    const idRows = db.prepare(`SELECT id FROM memories WHERE ${where}`).all(...params);
    let deleted = 0;
    for (const row of idRows) {
        if (deleteMemory(row.id, { type: 'cli', identifier: 'maintenance:prune' }))
            deleted++;
    }
    result.deleted = deleted;
    return result;
}
