"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportCIBuild = reportCIBuild;
exports.reportCITest = reportCITest;
exports.reportCIDeploy = reportCIDeploy;
exports.getCISummary = getCISummary;
exports.detectCIFailurePatterns = detectCIFailurePatterns;
exports.getBuildTrend = getBuildTrend;
exports.formatCISummary = formatCISummary;
const database_1 = require("../database/database");
const memory_event_store_1 = require("../stores/memory-event-store");
function reportCIBuild(result) {
    const topic = result.status === 'failure' ? 'ci-build-failed' : 'ci-build';
    const type = result.status === 'failure' ? 'error' : 'verification';
    const importance = result.status === 'failure' ? 7 : 5;
    const summary = `Build ${result.status}: ${result.stage} [${result.ciPlatform}] ${result.commitHash.slice(0, 8)}`;
    const event = {
        project: result.project,
        branch: result.branch,
        type,
        topic,
        summary,
        details: {
            buildId: result.buildId,
            status: result.status,
            duration: result.duration,
            stage: result.stage,
            commitHash: result.commitHash,
            commitMessage: result.commitMessage,
            author: result.author,
            ciPlatform: result.ciPlatform,
            logSnippet: result.logSnippet,
            source: 'ci-reporter',
        },
        files: [],
        importance,
        tool: 'cell-ci',
    };
    return (0, memory_event_store_1.recordMemoryEvent)(event);
}
function reportCITest(result) {
    const allPassed = result.failed === 0;
    const type = allPassed ? 'verification' : 'error';
    const topic = allPassed ? 'ci-test-passed' : 'ci-test-failed';
    const importance = result.failed > 0 ? 7 : 4;
    const summary = `Tests: ${result.passed}/${result.totalTests} passed` +
        (result.failed > 0 ? `, ${result.failed} failed` : '') +
        (result.skipped > 0 ? `, ${result.skipped} skipped` : '') +
        (result.coverage !== undefined ? ` (${result.coverage}% coverage)` : '');
    const event = {
        project: result.project,
        branch: result.branch,
        type,
        topic,
        summary,
        details: {
            buildId: result.buildId,
            totalTests: result.totalTests,
            passed: result.passed,
            failed: result.failed,
            skipped: result.skipped,
            duration: result.duration,
            failedTests: result.failedTests,
            coverage: result.coverage,
            source: 'ci-reporter',
        },
        files: [],
        importance,
        tool: 'cell-ci',
    };
    return (0, memory_event_store_1.recordMemoryEvent)(event);
}
function reportCIDeploy(result) {
    const type = result.status === 'success' ? 'publish' : 'error';
    const topic = result.status === 'success' ? 'ci-deploy' : 'ci-deploy-failed';
    const importance = result.status === 'failed' ? 8 : 6;
    const summary = `Deploy ${result.status}: ${result.version} → ${result.environment}` +
        (result.status === 'rolled_back' ? ' (rolled back)' : '');
    const event = {
        project: result.project,
        branch: '',
        type,
        topic,
        summary,
        details: {
            environment: result.environment,
            status: result.status,
            version: result.version,
            duration: result.duration,
            source: 'ci-reporter',
        },
        files: [],
        importance,
        tool: 'cell-ci',
    };
    return (0, memory_event_store_1.recordMemoryEvent)(event);
}
function getCISummary(project, days = 30) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const builds = db.prepare(`
    SELECT details_json, type FROM memory_events
    WHERE project = ? AND topic LIKE 'ci-build%' AND created_at >= ?
  `).all(project, since);
    const tests = db.prepare(`
    SELECT details_json, type FROM memory_events
    WHERE project = ? AND topic LIKE 'ci-test%' AND created_at >= ?
  `).all(project, since);
    const deploys = db.prepare(`
    SELECT details_json, type FROM memory_events
    WHERE project = ? AND topic LIKE 'ci-deploy%' AND created_at >= ?
  `).all(project, since);
    // Build stats
    let totalBuilds = builds.length;
    let successfulBuilds = 0;
    let totalDuration = 0;
    for (const b of builds) {
        try {
            const d = JSON.parse(b.details_json);
            if (d.status === 'success')
                successfulBuilds++;
            totalDuration += d.duration || 0;
        }
        catch { }
    }
    // Test stats
    let totalTests = 0;
    let totalPassed = 0;
    for (const t of tests) {
        try {
            const d = JSON.parse(t.details_json);
            totalTests += d.totalTests || 0;
            totalPassed += d.passed || 0;
        }
        catch { }
    }
    // Deploy stats
    let totalDeploys = deploys.length;
    let successfulDeploys = 0;
    for (const d of deploys) {
        try {
            const details = JSON.parse(d.details_json);
            if (details.status === 'success')
                successfulDeploys++;
        }
        catch { }
    }
    const successRate = totalBuilds > 0 ? Math.round(successfulBuilds / totalBuilds * 100) : 0;
    const testPassRate = totalTests > 0 ? Math.round(totalPassed / totalTests * 100) : 0;
    const deploySuccessRate = totalDeploys > 0 ? Math.round(successfulDeploys / totalDeploys * 100) : 0;
    const avgBuildDuration = totalBuilds > 0 ? Math.round(totalDuration / totalBuilds) : 0;
    const failurePatterns = detectCIFailurePatterns(project, days);
    return {
        totalBuilds,
        successRate,
        avgBuildDuration,
        totalTests,
        testPassRate,
        deployments: totalDeploys,
        deploySuccessRate,
        failurePatterns,
    };
}
function detectCIFailurePatterns(project, days = 30) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const failures = db.prepare(`
    SELECT summary, branch, created_at FROM memory_events
    WHERE project = ? AND type = 'error' AND (topic LIKE 'ci-%')
    AND created_at >= ? ORDER BY created_at
  `).all(project, since);
    if (failures.length === 0)
        return [];
    // Group by summary pattern
    const patternMap = new Map();
    for (const f of failures) {
        // Normalize: remove commit hashes, IDs, timestamps
        const pattern = f.summary
            .replace(/\[[a-f0-9]{8}\]/g, '[hash]')
            .replace(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/g, '[time]')
            .replace(/run[_-]?\d+/gi, '[run]')
            .slice(0, 100);
        const existing = patternMap.get(pattern) || {
            count: 0,
            firstSeen: f.created_at,
            lastSeen: f.created_at,
            branches: new Set(),
        };
        existing.count++;
        if (f.created_at < existing.firstSeen)
            existing.firstSeen = f.created_at;
        if (f.created_at > existing.lastSeen)
            existing.lastSeen = f.created_at;
        existing.branches.add(f.branch);
        patternMap.set(pattern, existing);
    }
    const patterns = [];
    for (const [pattern, data] of patternMap) {
        if (data.count < 2)
            continue; // Only report patterns with 2+ occurrences
        patterns.push({
            pattern,
            count: data.count,
            firstSeen: data.firstSeen,
            lastSeen: data.lastSeen,
            affectedBranches: [...data.branches],
            severity: data.count >= 5 ? 'critical' : data.count >= 2 ? 'warning' : 'info',
            suggestion: data.count >= 5
                ? 'Frequent failure — investigate root cause immediately'
                : 'Recurring failure — consider adding retries or fixing root cause',
        });
    }
    return patterns.sort((a, b) => b.count - a.count).slice(0, 10);
}
function getBuildTrend(project, days = 14) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const rows = db.prepare(`
    SELECT date(created_at) as date, details_json FROM memory_events
    WHERE project = ? AND topic LIKE 'ci-build%' AND created_at >= ?
    ORDER BY date
  `).all(project, since);
    const dayMap = new Map();
    for (const r of rows) {
        const existing = dayMap.get(r.date) || { total: 0, successes: 0 };
        existing.total++;
        try {
            const d = JSON.parse(r.details_json);
            if (d.status === 'success')
                existing.successes++;
        }
        catch { }
        dayMap.set(r.date, existing);
    }
    return [...dayMap.entries()].map(([date, data]) => ({
        date,
        builds: data.total,
        successes: data.successes,
        failures: data.total - data.successes,
        successRate: data.total > 0 ? Math.round(data.successes / data.total * 100) : 0,
    }));
}
function formatCISummary(summary) {
    const lines = [];
    lines.push('## CI/CD Summary\n');
    lines.push('| Metric | Value |');
    lines.push('|--------|-------|');
    lines.push(`| Total builds | ${summary.totalBuilds} |`);
    lines.push(`| Build success rate | ${summary.successRate}% |`);
    lines.push(`| Avg build duration | ${formatDuration(summary.avgBuildDuration)} |`);
    lines.push(`| Total tests | ${summary.totalTests} |`);
    lines.push(`| Test pass rate | ${summary.testPassRate}% |`);
    lines.push(`| Deployments | ${summary.deployments} |`);
    lines.push(`| Deploy success rate | ${summary.deploySuccessRate}% |`);
    if (summary.failurePatterns.length > 0) {
        lines.push('\n### Failure Patterns');
        for (const p of summary.failurePatterns) {
            lines.push(`- [${p.severity}] ${p.pattern} (×${p.count}, branches: ${p.affectedBranches.join(', ')})`);
        }
    }
    return lines.join('\n');
}
function formatDuration(ms) {
    if (ms === 0)
        return 'N/A';
    if (ms < 60000)
        return `${Math.round(ms / 1000)}s`;
    if (ms < 3600000)
        return `${Math.round(ms / 60000)}m`;
    return `${(ms / 3600000).toFixed(1)}h`;
}
//# sourceMappingURL=ci-reporter.js.map