/**
 * Secrets usage read-model — thin adapter over the analytics usage warehouse
 * (`kind=secret`). Kept so `secrets view` / `list` / `activity` keep their API
 * while the durable store lives at ~/.agents/.history/analytics/usage.db.
 */
import { recordUsage, getSecretBundleRollup, getSecretBundleAgents, getAllSecretBundleRollups, getSecretHistory, closeUsageDb, } from '../analytics/usage-db.js';
export const SECRET_USAGE_EVENTS = [
    'access',
    'unlock',
    'import',
    'export',
    'create',
    'view',
];
function emptyEvents() {
    return {
        access: { count: 0, last: null },
        unlock: { count: 0, last: null },
        import: { count: 0, last: null },
        export: { count: 0, last: null },
        create: { count: 0, last: null },
        view: { count: 0, last: null },
    };
}
function toSummary(bundle, rows, byAgent) {
    const events = emptyEvents();
    let total = 0;
    let lastUsedAt = null;
    let firstUsedAt = null;
    for (const r of rows) {
        if (r.event in events) {
            const stat = events[r.event];
            stat.count = r.n;
            stat.last = r.last;
        }
        total += r.n;
        if (r.last && (!lastUsedAt || r.last > lastUsedAt))
            lastUsedAt = r.last;
        if (r.first && (!firstUsedAt || r.first < firstUsedAt))
            firstUsedAt = r.first;
    }
    return { bundle, total, events, lastUsedAt, firstUsedAt, byAgent };
}
export function recordSecretUsage(p) {
    if (!p.bundle)
        return;
    const meta = {};
    if (p.keyCount != null)
        meta.keyCount = p.keyCount;
    if (p.host)
        meta.host = p.host;
    recordUsage({
        kind: 'secret',
        name: p.bundle,
        event: p.event,
        agent: p.agent,
        source: p.source,
        status: p.status,
        meta: Object.keys(meta).length ? meta : undefined,
    });
}
export function getBundleUsage(bundle) {
    const rows = getSecretBundleRollup(bundle);
    if (rows.length === 0)
        return undefined;
    const agents = getSecretBundleAgents(bundle);
    return toSummary(bundle, rows, agents.map((a) => ({ agent: a.agent, count: a.n })));
}
export function getAllBundleUsage() {
    const out = new Map();
    const rows = getAllSecretBundleRollups();
    const byBundle = new Map();
    for (const r of rows) {
        const list = byBundle.get(r.name) ?? [];
        list.push(r);
        byBundle.set(r.name, list);
    }
    for (const [bundle, list] of byBundle)
        out.set(bundle, toSummary(bundle, list, []));
    return out;
}
export function getUsageHistory(bundle, limit = 20) {
    return getSecretHistory(bundle, limit).map((r) => ({
        ts: r.ts,
        bundle: r.bundle,
        event: r.event,
        agent: r.agent,
        host: r.host,
        source: r.source,
        status: r.status,
        keyCount: r.keyCount,
    }));
}
export function closeSecretsUsageDb() {
    closeUsageDb();
}
