/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, renameSync, writeFileSync } from 'node:fs';
import { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { listRecords, recordPath } from '../../../services/orchestration-records.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.evidence.compact');
export default class EvidenceCompact extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        'older-than-days': Flags.integer({
            char: 'd',
            summary: messages.getMessage('flags.older-than-days.summary'),
            description: messages.getMessage('flags.older-than-days.description'),
            default: 30,
            min: 1,
        }),
        'dry-run': Flags.boolean({
            summary: messages.getMessage('flags.dry-run.summary'),
            default: false,
        }),
        task: Flags.string({
            char: 't',
            summary: messages.getMessage('flags.task.summary'),
            description: messages.getMessage('flags.task.description'),
        }),
    };
    async run() {
        const { flags } = await this.parse(EvidenceCompact);
        const cwd = process.cwd();
        const evidenceFile = recordPath(cwd, 'evidence');
        if (!existsSync(evidenceFile)) {
            this.log(messages.getMessage('info.empty'));
            return { originalCount: 0, compactedCount: 0, archivedFile: null, cwd };
        }
        const allRecords = listRecords(cwd, 'evidence');
        const originalCount = allRecords.length;
        const cutoff = Date.now() - flags['older-than-days'] * 24 * 60 * 60 * 1000;
        const { keep, archive } = partitionRecords(allRecords, cutoff, flags.task);
        if (archive.length === 0) {
            this.log(messages.getMessage('info.nothingToCompact'));
            return { originalCount, compactedCount: originalCount, archivedFile: null, cwd };
        }
        const summaryEntry = buildSummaryEntry(archive);
        if (flags['dry-run']) {
            this.log(messages.getMessage('info.dryRun', [String(archive.length), String(keep.length)]));
            return { originalCount, compactedCount: keep.length + 1, archivedFile: null, cwd };
        }
        const archivedFile = `${evidenceFile}.archive-${Date.now()}`;
        renameSync(evidenceFile, archivedFile);
        const finalRecords = [summaryEntry, ...keep];
        writeFileSync(evidenceFile, finalRecords.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8');
        this.log(messages.getMessage('info.compacted', [String(archive.length), String(finalRecords.length), archivedFile]));
        return { originalCount, compactedCount: finalRecords.length, archivedFile, cwd };
    }
}
function buildSummaryEntry(archived) {
    const taskIds = [...new Set(archived.flatMap((r) => r.taskIds))];
    const kinds = [...new Set(archived.map((r) => r.evidenceKind))];
    const summaryLines = [];
    const byKind = new Map();
    for (const r of archived) {
        const list = byKind.get(r.evidenceKind) ?? [];
        list.push(r);
        byKind.set(r.evidenceKind, list);
    }
    for (const [evidenceKind, records] of byKind) {
        summaryLines.push(`[${evidenceKind}] ${records.length} entries:`);
        for (const r of records.slice(0, 5)) {
            summaryLines.push(`  - ${r.summary.slice(0, 120)}`);
        }
        if (records.length > 5) {
            summaryLines.push(`  ... and ${records.length - 5} more`);
        }
    }
    return {
        id: `evidence-summary-${Date.now()}`,
        kind: 'evidence',
        summary: `Compacted summary of ${archived.length} entries (kinds: ${kinds.join(', ')})\n${summaryLines.join('\n')}`,
        evidenceKind: 'report',
        taskIds,
        createdAt: new Date().toISOString(),
    };
}
function partitionRecords(records, cutoffMs, taskFilter) {
    const keep = [];
    const archive = [];
    for (const record of records) {
        const recordTime = new Date(record.createdAt).getTime();
        const isOld = recordTime < cutoffMs;
        const matchesTask = taskFilter ? record.taskIds.includes(taskFilter) : true;
        if (isOld && matchesTask) {
            archive.push(record);
        }
        else {
            keep.push(record);
        }
    }
    return { keep, archive };
}
//# sourceMappingURL=compact.js.map