"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDailySummary = generateDailySummary;
exports.saveDailySummary = saveDailySummary;
exports.generateWeeklySummary = generateWeeklySummary;
exports.saveWeeklySummary = saveWeeklySummary;
exports.generateMonthlySummary = generateMonthlySummary;
exports.saveMonthlySummary = saveMonthlySummary;
exports.generateSessionSummary = generateSessionSummary;
exports.generateTopicSummary = generateTopicSummary;
exports.generateBranchSummary = generateBranchSummary;
exports.generateFileSummary = generateFileSummary;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
function generateDailySummary(project, date) {
    const targetDate = date || new Date().toISOString().slice(0, 10);
    const db = (0, database_1.getDb)();
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json FROM memory_events
     WHERE project = ? AND date(created_at) = date(?)
     ORDER BY importance DESC`).all(project, targetDate);
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                const files = JSON.parse(row.files_json);
                files.forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5)
        .map(([t]) => t);
    return {
        date: targetDate,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions,
        errors,
        filesChanged: Array.from(filesSet).slice(0, 20),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function saveDailySummary(project, projectDir, date) {
    const summary = generateDailySummary(project, date);
    const summaryDir = path.join(projectDir, '.cell', 'memory', 'summaries', 'daily');
    if (!fs.existsSync(summaryDir))
        fs.mkdirSync(summaryDir, { recursive: true });
    const filePath = path.join(summaryDir, `${summary.date}.json`);
    fs.writeFileSync(filePath, JSON.stringify(summary, null, 2));
    return filePath;
}
function generateWeeklySummary(project, projectDir) {
    const db = (0, database_1.getDb)();
    const end = new Date();
    const start = new Date(end.getTime() - 7 * 86400000);
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json, created_at FROM memory_events
     WHERE project = ? AND date(created_at) >= date(?)
     ORDER BY importance DESC`).all(project, start.toISOString().slice(0, 10));
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                JSON.parse(row.files_json).forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10)
        .map(([t]) => t);
    return {
        date: `${start.toISOString().slice(0, 10)}_to_${end.toISOString().slice(0, 10)}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions: keyDecisions.slice(0, 10),
        errors: errors.slice(0, 10),
        filesChanged: Array.from(filesSet).slice(0, 50),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function saveWeeklySummary(project, projectDir) {
    const summary = generateWeeklySummary(project, projectDir);
    const summaryDir = path.join(projectDir, '.cell', 'memory', 'summaries', 'weekly');
    if (!fs.existsSync(summaryDir))
        fs.mkdirSync(summaryDir, { recursive: true });
    const filePath = path.join(summaryDir, `${summary.date}.json`);
    fs.writeFileSync(filePath, JSON.stringify(summary, null, 2));
    return filePath;
}
function generateMonthlySummary(project, projectDir) {
    const db = (0, database_1.getDb)();
    const end = new Date();
    const start = new Date(end.getFullYear(), end.getMonth() - 1, end.getDate());
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json, created_at FROM memory_events
     WHERE project = ? AND date(created_at) >= date(?)
     ORDER BY importance DESC`).all(project, start.toISOString().slice(0, 10));
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                JSON.parse(row.files_json).forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 15)
        .map(([t]) => t);
    return {
        date: `${start.toISOString().slice(0, 10)}_to_${end.toISOString().slice(0, 10)}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions: keyDecisions.slice(0, 20),
        errors: errors.slice(0, 20),
        filesChanged: Array.from(filesSet).slice(0, 100),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function saveMonthlySummary(project, projectDir) {
    const summary = generateMonthlySummary(project, projectDir);
    const summaryDir = path.join(projectDir, '.cell', 'memory', 'summaries', 'monthly');
    if (!fs.existsSync(summaryDir))
        fs.mkdirSync(summaryDir, { recursive: true });
    const filePath = path.join(summaryDir, `${summary.date}.json`);
    fs.writeFileSync(filePath, JSON.stringify(summary, null, 2));
    return filePath;
}
function generateSessionSummary(project, sessionId) {
    const db = (0, database_1.getDb)();
    const sessionRow = db.prepare('SELECT start_time, end_time FROM sessions WHERE id = ?').get(sessionId);
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json FROM memory_events
     WHERE project = ? AND created_at >= ? AND created_at <= ?
     ORDER BY importance DESC`).all(project, sessionRow?.start_time || new Date().toISOString(), sessionRow?.end_time || new Date().toISOString());
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                JSON.parse(row.files_json).forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10)
        .map(([t]) => t);
    return {
        date: `session_${sessionId}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions,
        errors,
        filesChanged: Array.from(filesSet).slice(0, 50),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function generateTopicSummary(project, topic) {
    const db = (0, database_1.getDb)();
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json FROM memory_events
     WHERE project = ? AND topic = ?
     ORDER BY importance DESC`).all(project, topic);
    const byType = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                JSON.parse(row.files_json).forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    return {
        date: `topic_${topic}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics: [topic],
        keyDecisions,
        errors,
        filesChanged: Array.from(filesSet).slice(0, 50),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function generateBranchSummary(project, branch) {
    const db = (0, database_1.getDb)();
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json FROM memory_events
     WHERE project = ? AND branch = ?
     ORDER BY importance DESC`).all(project, branch);
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    const filesSet = new Set();
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
        if (row.files_json) {
            try {
                JSON.parse(row.files_json).forEach(f => filesSet.add(f));
            }
            catch { }
        }
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10)
        .map(([t]) => t);
    return {
        date: `branch_${branch}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions,
        errors,
        filesChanged: Array.from(filesSet).slice(0, 50),
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
function generateFileSummary(project, filePath) {
    const db = (0, database_1.getDb)();
    const rows = db.prepare(`SELECT type, topic, summary, importance, files_json FROM memory_events
     WHERE project = ? AND files_json LIKE ?
     ORDER BY importance DESC`).all(project, `%${filePath}%`);
    const byType = {};
    const topicCounts = {};
    const keyDecisions = [];
    const errors = [];
    let totalImportance = 0;
    for (const row of rows) {
        byType[row.type] = (byType[row.type] || 0) + 1;
        if (row.topic)
            topicCounts[row.topic] = (topicCounts[row.topic] || 0) + 1;
        totalImportance += row.importance;
        if (row.type === 'decision')
            keyDecisions.push(row.summary);
        if (row.type === 'error')
            errors.push(row.summary);
    }
    const topTopics = Object.entries(topicCounts)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5)
        .map(([t]) => t);
    return {
        date: `file_${filePath.replace(/[\/\\]/g, '_')}`,
        project,
        totalEvents: rows.length,
        byType,
        topTopics,
        keyDecisions,
        errors,
        filesChanged: [filePath],
        importance: rows.length > 0 ? Math.round(totalImportance / rows.length * 10) / 10 : 0,
    };
}
//# sourceMappingURL=summary-generator.js.map