/**
 * System metrics aggregation core module.
 * @task T4783
 */
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { readComplianceJsonl } from '../compliance/store.js';
/** Get system metrics: token usage, compliance summary, session counts. */
export async function getSystemMetrics(projectRoot, opts, accessor) {
    const cleoDir = join(projectRoot, '.cleo');
    // Compliance metrics
    let complianceEntries = readComplianceJsonl(projectRoot);
    if (opts?.since) {
        complianceEntries = complianceEntries.filter((e) => e.timestamp >= opts.since);
    }
    const totalCompliance = complianceEntries.length;
    let passed = 0;
    let failed = 0;
    let scoreSum = 0;
    for (const e of complianceEntries) {
        const c = (e.compliance ?? {});
        const violations = c.violation_count ?? 0;
        if (violations === 0)
            passed++;
        else
            failed++;
        scoreSum += c.compliance_pass_rate ?? 0;
    }
    const avgScore = totalCompliance > 0 ? Math.round((scoreSum / totalCompliance) * 1000) / 1000 : 0;
    // Session metrics
    let sessionsTotal = 0;
    let sessionsActive = 0;
    let sessionsCompleted = 0;
    try {
        if (accessor) {
            const sessions = await accessor.loadSessions();
            sessionsTotal = sessions.length;
            sessionsActive = sessions.filter((s) => s.status === 'active').length;
            sessionsCompleted = sessions.filter((s) => s.status === 'ended').length;
        }
        else {
            const sessionsPath = join(cleoDir, 'sessions.json');
            if (existsSync(sessionsPath)) {
                const sessionsData = JSON.parse(readFileSync(sessionsPath, 'utf-8'));
                const sessions = sessionsData.sessions ?? [];
                sessionsTotal = sessions.length;
                sessionsActive = sessions.filter((s) => s.status === 'active').length;
                sessionsCompleted = sessions.filter((s) => s.status === 'ended' || s.status === 'ended').length;
            }
        }
    }
    catch {
        // skip
    }
    return {
        tokens: { input: 0, output: 0, cache: 0, total: 0 },
        compliance: { total: totalCompliance, passed, failed, score: avgScore },
        sessions: { total: sessionsTotal, active: sessionsActive, completed: sessionsCompleted },
    };
}
//# sourceMappingURL=metrics.js.map