"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.generateWeeklyReport = generateWeeklyReport;
exports.saveWeeklyReport = saveWeeklyReport;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
function generateWeeklyReport(project, projectDir) {
    const db = (0, database_1.getDb)();
    const now = new Date();
    const weekEnd = now.toISOString().slice(0, 10);
    const weekStart = new Date(now.getTime() - 7 * 86400000).toISOString().slice(0, 10);
    const since = new Date(now.getTime() - 7 * 86400000).toISOString();
    // Events
    const events = db.prepare(`
    SELECT type, summary, importance, topic, created_at FROM memory_events
    WHERE project = ? AND created_at >= ?
    ORDER BY importance DESC
  `).all(project, since);
    const totalEvents = events.length;
    const avgImportance = totalEvents > 0
        ? Math.round(events.reduce((s, e) => s + e.importance, 0) / totalEvents * 10) / 10
        : 0;
    // By type
    const byType = {};
    for (const e of events)
        byType[e.type] = (byType[e.type] || 0) + 1;
    // Topics
    const topicMap = new Map();
    for (const e of events) {
        if (e.topic)
            topicMap.set(e.topic, (topicMap.get(e.topic) || 0) + 1);
    }
    const topTopics = [...topicMap.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([t]) => t);
    // Decisions, errors, fixes
    const keyDecisions = events.filter(e => e.type === 'decision').slice(0, 10).map(e => e.summary);
    const errors = events.filter(e => e.type === 'error').slice(0, 10).map(e => e.summary);
    const fixes = events.filter(e => e.type === 'fix').slice(0, 10).map(e => e.summary);
    // Insights from memory_insights
    let insights = [];
    try {
        const { generateMemoryInsights } = require('./memory-insights');
        const memInsights = generateMemoryInsights(project, 7);
        insights = memInsights.slice(0, 5).map((i) => `${i.title}: ${i.description}`);
    }
    catch { }
    // Handoff summary
    let handoffSummary = 'No handoff data';
    try {
        const handoffPath = projectDir
            ? path.join(projectDir, '.cell', 'handoff', 'current.md')
            : path.join(process.cwd(), '.cell', 'handoff', 'current.md');
        if (fs.existsSync(handoffPath)) {
            const content = fs.readFileSync(handoffPath, 'utf-8');
            const lines = content.split('\n').filter(l => l.trim());
            handoffSummary = lines.slice(0, 10).join('\n');
        }
    }
    catch { }
    // Productivity score (0-10)
    const productivityScore = calcProductivityScore(events, totalEvents, keyDecisions.length, errors.length, fixes.length);
    // CI summary
    let ciSummary = { totalBuilds: 0, successRate: 0, failures: [] };
    try {
        const ciEvents = db.prepare(`SELECT type, summary, topic, importance, created_at FROM memory_events
       WHERE project = ? AND created_at >= ? AND topic LIKE 'ci-%'
       ORDER BY created_at DESC`).all(project, since);
        ciSummary.totalBuilds = ciEvents.length;
        const successes = ciEvents.filter(e => e.topic === 'ci-build' || e.topic === 'ci-test-passed').length;
        ciSummary.successRate = ciEvents.length > 0 ? Math.round(successes / ciEvents.length * 100) : 100;
        ciSummary.failures = ciEvents.filter(e => e.topic === 'ci-build-failed' || e.topic === 'ci-test-failed').slice(0, 5).map(e => e.summary);
    }
    catch { /* ignore */ }
    // Generate markdown
    const markdown = buildMarkdownReport(project, weekStart, weekEnd, totalEvents, avgImportance, byType, topTopics, keyDecisions, errors, fixes, insights, handoffSummary, productivityScore, ciSummary);
    return {
        project,
        weekStart,
        weekEnd,
        totalEvents,
        avgImportance,
        byType,
        topTopics,
        keyDecisions,
        errors,
        fixes,
        insights,
        handoffSummary,
        productivityScore,
        ciSummary,
        markdown,
    };
}
function saveWeeklyReport(report, projectDir) {
    const dir = projectDir
        ? path.join(projectDir, '.cell', 'memory', 'summaries', 'weekly')
        : path.join(process.cwd(), '.cell', 'memory', 'summaries', 'weekly');
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    const filePath = path.join(dir, `${report.weekEnd}.md`);
    fs.writeFileSync(filePath, report.markdown, 'utf-8');
    return filePath;
}
function calcProductivityScore(events, total, decisions, errors, fixes) {
    if (total === 0)
        return 0;
    let score = 5;
    // Bonus for decisions
    if (decisions > 3)
        score += 1.5;
    else if (decisions > 0)
        score += 0.5;
    // Bonus for fixes after errors
    if (errors > 0 && fixes > 0)
        score += 1;
    // Penalty for high error rate
    if (errors > total * 0.3)
        score -= 2;
    else if (errors > total * 0.15)
        score -= 1;
    // Bonus for high avg importance
    const avgImp = events.reduce((s, e) => s + e.importance, 0) / total;
    if (avgImp > 6)
        score += 1;
    // Bonus for volume
    if (total > 20)
        score += 0.5;
    return Math.max(1, Math.min(10, Math.round(score * 10) / 10));
}
function buildMarkdownReport(project, weekStart, weekEnd, totalEvents, avgImportance, byType, topTopics, keyDecisions, errors, fixes, insights, handoffSummary, productivityScore, ciSummary) {
    const lines = [];
    lines.push(`# Weekly Report — ${project}`);
    lines.push(`**${weekStart} → ${weekEnd}**\n`);
    lines.push(`## Overview`);
    lines.push(`| Metric | Value |`);
    lines.push(`|--------|-------|`);
    lines.push(`| Total events | ${totalEvents} |`);
    lines.push(`| Avg importance | ${avgImportance} |`);
    lines.push(`| Productivity score | ${productivityScore}/10 |`);
    if (ciSummary.totalBuilds > 0) {
        lines.push(`| CI builds | ${ciSummary.totalBuilds} (${ciSummary.successRate}% success) |`);
    }
    lines.push('');
    if (ciSummary.totalBuilds > 0 && ciSummary.failures.length > 0) {
        lines.push(`## CI Failures`);
        for (const f of ciSummary.failures)
            lines.push(`- ${f}`);
        lines.push('');
    }
    if (topTopics.length > 0) {
        lines.push(`## Top Topics`);
        for (const t of topTopics)
            lines.push(`- ${t}`);
        lines.push('');
    }
    if (Object.keys(byType).length > 0) {
        lines.push(`## Activity Breakdown`);
        for (const [type, count] of Object.entries(byType).sort((a, b) => b[1] - a[1])) {
            lines.push(`- **${type}**: ${count}`);
        }
        lines.push('');
    }
    if (keyDecisions.length > 0) {
        lines.push(`## Key Decisions`);
        for (const d of keyDecisions)
            lines.push(`- ${d}`);
        lines.push('');
    }
    if (errors.length > 0) {
        lines.push(`## Errors`);
        for (const e of errors)
            lines.push(`- ${e}`);
        lines.push('');
    }
    if (fixes.length > 0) {
        lines.push(`## Fixes Applied`);
        for (const f of fixes)
            lines.push(`- ${f}`);
        lines.push('');
    }
    if (insights.length > 0) {
        lines.push(`## Insights`);
        for (const i of insights)
            lines.push(`- ${i}`);
        lines.push('');
    }
    lines.push(`## Handoff Context`);
    lines.push('```');
    lines.push(handoffSummary);
    lines.push('```\n');
    lines.push(`---`);
    lines.push(`*Generated by FIVO Cell v5.0.0*`);
    return lines.join('\n');
}
//# sourceMappingURL=weekly-report.js.map