/**
 * Forensic query helpers for the defence audit log
 */
import { getDatabase } from '../../database/init.js';
// ── Query Functions ──
/**
 * Query audit logs with flexible filters.
 */
export function queryAuditLogs(options = {}) {
    const db = getDatabase();
    const conditions = [];
    const params = {};
    if (options.startTime) {
        conditions.push('da.timestamp >= @startTime');
        params.startTime = options.startTime;
    }
    if (options.endTime) {
        conditions.push('da.timestamp <= @endTime');
        params.endTime = options.endTime;
    }
    if (options.firewallResult) {
        conditions.push('da.firewall_result = @firewallResult');
        params.firewallResult = options.firewallResult;
    }
    if (options.source) {
        conditions.push('da.source_type = @source');
        params.source = options.source;
    }
    if (options.memoryId !== undefined) {
        conditions.push('da.memory_id = @memoryId');
        params.memoryId = options.memoryId;
    }
    if (options.project) {
        conditions.push('da.project = @project');
        params.project = options.project;
    }
    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const limit = options.limit ?? 50;
    const sql = `SELECT da.* FROM defence_audit da ${where} ORDER BY da.timestamp DESC LIMIT @limit`;
    params.limit = limit;
    return db.prepare(sql).all(params);
}
/**
 * Get aggregate audit statistics for a time range.
 */
export function getAuditStats(timeRange, project) {
    const db = getDatabase();
    const hoursMap = { '24h': 24, '7d': 168, '30d': 720 };
    const hours = hoursMap[timeRange];
    const since = new Date(Date.now() - hours * 3600_000).toISOString();
    const projectCond = project ? 'AND da.project = ?' : '';
    const baseParams = project ? [since, project] : [since];
    // Counts by firewall result
    const counts = db.prepare(`
    SELECT da.firewall_result, COUNT(*) as cnt
    FROM defence_audit da
    WHERE da.timestamp >= ? ${projectCond}
    GROUP BY da.firewall_result
  `).all(...baseParams);
    let totalOperations = 0;
    let allowedCount = 0;
    let blockedCount = 0;
    let quarantinedCount = 0;
    for (const row of counts) {
        totalOperations += row.cnt;
        if (row.firewall_result === 'ALLOW')
            allowedCount = row.cnt;
        else if (row.firewall_result === 'BLOCK')
            blockedCount = row.cnt;
        else if (row.firewall_result === 'QUARANTINE')
            quarantinedCount = row.cnt;
    }
    // Top sources
    const topSources = db.prepare(`
    SELECT da.source_type as source, COUNT(*) as count
    FROM defence_audit da
    WHERE da.timestamp >= ? ${projectCond}
    GROUP BY da.source_type
    ORDER BY count DESC
    LIMIT 10
  `).all(...baseParams);
    // Threat indicator breakdown
    const rows = db.prepare(`
    SELECT da.threat_indicators
    FROM defence_audit da
    WHERE da.timestamp >= ? ${projectCond} AND da.threat_indicators != '[]'
  `).all(...baseParams);
    const threatBreakdown = {};
    for (const row of rows) {
        try {
            const indicators = JSON.parse(row.threat_indicators);
            for (const indicator of indicators) {
                threatBreakdown[indicator] = (threatBreakdown[indicator] ?? 0) + 1;
            }
        }
        catch {
            // Skip malformed JSON
        }
    }
    return {
        totalOperations,
        allowedCount,
        blockedCount,
        quarantinedCount,
        topSources,
        threatBreakdown,
    };
}
// ── Agent Query Functions ──
/**
 * Get distinct agents aggregated from audit logs.
 */
export function queryAgentRegistry(timeRange = '24h', project) {
    const db = getDatabase();
    const hoursMap = { '24h': 24, '7d': 168, '30d': 720 };
    const since = new Date(Date.now() - hoursMap[timeRange] * 3600_000).toISOString();
    const projectCond = project ? 'AND project = ?' : '';
    const params = project ? [since, project] : [since];
    return db.prepare(`
    SELECT source_type, source_identifier,
      COUNT(*) as operation_count,
      MAX(timestamp) as last_seen,
      AVG(trust_score) as avg_trust_score,
      MIN(trust_score) as min_trust_score,
      MAX(trust_score) as max_trust_score,
      SUM(CASE WHEN firewall_result != 'ALLOW' THEN 1 ELSE 0 END) as flagged_count
    FROM defence_audit
    WHERE timestamp >= ? ${projectCond}
    GROUP BY source_type, source_identifier
    ORDER BY operation_count DESC
  `).all(...params);
}
/**
 * Get trust score timeline for a specific agent.
 */
export function queryAgentTimeline(identifier, timeRange = '24h', project) {
    const db = getDatabase();
    const hoursMap = { '24h': 24, '7d': 168, '30d': 720 };
    const since = new Date(Date.now() - hoursMap[timeRange] * 3600_000).toISOString();
    const projectCond = project ? 'AND project = ?' : '';
    const params = project ? [identifier, since, project] : [identifier, since];
    return db.prepare(`
    SELECT timestamp, trust_score, firewall_result, anomaly_score
    FROM defence_audit
    WHERE source_identifier = ? AND timestamp >= ? ${projectCond}
    ORDER BY timestamp ASC
  `).all(...params);
}
/**
 * Get paginated audit entries for a specific agent.
 */
export function queryAgentOperations(identifier, options = {}) {
    const db = getDatabase();
    const conditions = ['source_identifier = @identifier'];
    const params = { identifier };
    if (options.firewallResult) {
        conditions.push('firewall_result = @firewallResult');
        params.firewallResult = options.firewallResult;
    }
    if (options.project) {
        conditions.push('project = @project');
        params.project = options.project;
    }
    const limit = options.limit ?? 50;
    const offset = options.offset ?? 0;
    params.limit = limit;
    params.offset = offset;
    return db.prepare(`
    SELECT * FROM defence_audit
    WHERE ${conditions.join(' AND ')}
    ORDER BY timestamp DESC
    LIMIT @limit OFFSET @offset
  `).all(params);
}
//# sourceMappingURL=queries.js.map