"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeGrowthTrends = computeGrowthTrends;
exports.formatGrowthTrend = formatGrowthTrend;
const database_1 = require("../database/database");
function computeGrowthTrends(project, days = 30) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    // Daily event counts
    const dailyRows = db.prepare(`
    SELECT date(created_at) as date, COUNT(*) as count, AVG(importance) as avgImp
    FROM memory_events WHERE project = ? AND created_at >= ?
    GROUP BY date(created_at) ORDER BY date
  `).all(project, since);
    // Type breakdown per day
    const typeRows = db.prepare(`
    SELECT date(created_at) as date, type, COUNT(*) as count
    FROM memory_events WHERE project = ? AND created_at >= ?
    GROUP BY date(created_at), type ORDER BY date
  `).all(project, since);
    const typeByDay = {};
    for (const r of typeRows) {
        if (!typeByDay[r.date])
            typeByDay[r.date] = {};
        typeByDay[r.date][r.type] = r.count;
    }
    // Build data points
    const dataPoints = dailyRows.map((r, i) => ({
        date: r.date,
        totalEvents: dailyRows.slice(0, i + 1).reduce((s, d) => s + d.count, 0),
        newEvents: r.count,
        avgImportance: Math.round(r.avgImp * 10) / 10,
        types: typeByDay[r.date] || {},
    }));
    // Summary
    const totalRow = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ?').get(project);
    const since7d = new Date(Date.now() - 7 * 86400000).toISOString();
    const since30d = new Date(Date.now() - 30 * 86400000).toISOString();
    const last7d = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND created_at >= ?').get(project, since7d);
    const last30d = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND created_at >= ?').get(project, since30d);
    const avgDaily = dataPoints.length > 0
        ? Math.round(dataPoints.reduce((s, d) => s + d.newEvents, 0) / dataPoints.length * 10) / 10
        : 0;
    const peak = dataPoints.reduce((max, d) => d.newEvents > max.newEvents ? d : max, { date: 'none', newEvents: 0 });
    // Growth rate: compare last half vs first half
    const half = Math.floor(dataPoints.length / 2);
    const firstHalf = dataPoints.slice(0, half);
    const secondHalf = dataPoints.slice(half);
    const firstAvg = firstHalf.length > 0 ? firstHalf.reduce((s, d) => s + d.newEvents, 0) / firstHalf.length : 0;
    const secondAvg = secondHalf.length > 0 ? secondHalf.reduce((s, d) => s + d.newEvents, 0) / secondHalf.length : 0;
    const growthRate = firstAvg > 0 ? Math.round((secondAvg - firstAvg) / firstAvg * 100) : 0;
    let trend = 'steady';
    if (growthRate > 20)
        trend = 'accelerating';
    else if (growthRate > 5)
        trend = 'steady';
    else if (growthRate > -10)
        trend = 'decelerating';
    else
        trend = 'declining';
    const summary = {
        totalEvents: totalRow.c,
        eventsLast7d: last7d.c,
        eventsLast30d: last30d.c,
        avgDailyGrowth: avgDaily,
        peakDay: peak.date,
        peakDayCount: peak.newEvents,
        growthRate,
        trend,
    };
    // Prediction (simple linear extrapolation)
    const recentDays = dataPoints.slice(-7);
    const recentAvg = recentDays.length > 0
        ? recentDays.reduce((s, d) => s + d.newEvents, 0) / recentDays.length
        : avgDaily;
    const prediction = {
        next7dEstimate: Math.round(recentAvg * 7),
        next30dEstimate: Math.round(recentAvg * 30),
        confidence: dataPoints.length >= 14 ? 0.8 : dataPoints.length >= 7 ? 0.6 : 0.4,
        basedOnDays: dataPoints.length,
    };
    // ASCII Chart
    const chart = renderGrowthChart(dataPoints, summary);
    return {
        project,
        period: `${days}d`,
        dataPoints,
        summary,
        prediction,
        chart,
    };
}
function renderGrowthChart(points, summary) {
    if (points.length === 0)
        return '  No data available.';
    const maxEvents = Math.max(...points.map(p => p.newEvents), 1);
    const chartHeight = 10;
    const lines = [];
    lines.push(`  Memory Growth — ${summary.trend.toUpperCase()} (rate: ${summary.growthRate > 0 ? '+' : ''}${summary.growthRate}%)`);
    lines.push('');
    // Build chart rows
    for (let row = chartHeight; row >= 1; row--) {
        const threshold = (row / chartHeight) * maxEvents;
        const label = row === chartHeight ? String(maxEvents).padStart(4) : row === 1 ? '   1' : '    ';
        let line = `  ${label} │`;
        for (const p of points) {
            if (p.newEvents >= threshold) {
                line += ' █';
            }
            else {
                line += '  ';
            }
        }
        lines.push(line);
    }
    // X axis
    lines.push(`      └${'─'.repeat(points.length * 2)}`);
    // Date labels
    if (points.length > 0) {
        const first = points[0].date.slice(5);
        const last = points[points.length - 1].date.slice(5);
        lines.push(`       ${first}${' '.repeat(Math.max(0, points.length * 2 - first.length - last.length))}${last}`);
    }
    lines.push('');
    lines.push(`  Total: ${summary.totalEvents} | Last 7d: ${summary.eventsLast7d} | Avg/day: ${summary.avgDailyGrowth}`);
    return lines.join('\n');
}
function formatGrowthTrend(trend) {
    const lines = [];
    lines.push(`## Memory Growth — ${trend.project} (${trend.period})\n`);
    lines.push(trend.chart);
    lines.push('');
    lines.push(`### Summary`);
    lines.push(`| Metric | Value |`);
    lines.push(`|--------|-------|`);
    lines.push(`| Total events | ${trend.summary.totalEvents} |`);
    lines.push(`| Last 7d | ${trend.summary.eventsLast7d} |`);
    lines.push(`| Last 30d | ${trend.summary.eventsLast30d} |`);
    lines.push(`| Avg daily | ${trend.summary.avgDailyGrowth} |`);
    lines.push(`| Peak day | ${trend.summary.peakDay} (${trend.summary.peakDayCount}) |`);
    lines.push(`| Growth rate | ${trend.summary.growthRate > 0 ? '+' : ''}${trend.summary.growthRate}% |`);
    lines.push(`| Trend | ${trend.summary.trend} |`);
    lines.push('');
    lines.push(`### Prediction`);
    lines.push(`- Next 7d: ~${trend.prediction.next7dEstimate} events`);
    lines.push(`- Next 30d: ~${trend.prediction.next30dEstimate} events`);
    lines.push(`- Confidence: ${Math.round(trend.prediction.confidence * 100)}% (${trend.prediction.basedOnDays} days of data)`);
    return lines.join('\n');
}
//# sourceMappingURL=memory-growth.js.map