/*
 * 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 { randomBytes } from 'node:crypto';
import { join } from 'node:path';
import { err, ok } from '../types/index.js';
import { appendJsonlFile, compact, readJsonlFile } from './file-writer.js';
const RECORD_FILES = {
    decision: 'decisions.jsonl',
    evidence: 'evidence.jsonl',
    handoff: 'handoffs.jsonl',
    review: 'reviews.jsonl',
};
export function addEvidenceRecord(cwd, input) {
    const record = compact({
        id: nextId('evidence'),
        kind: 'evidence',
        createdAt: new Date().toISOString(),
        summary: input.summary,
        taskIds: input.taskIds ?? [],
        owner: input.profile ? profileOwner(input.profile) : undefined,
        evidenceKind: input.evidenceKind ?? 'other',
        command: input.command,
        path: input.path,
        exitCode: input.exitCode,
        details: input.details,
    });
    appendRecord(cwd, record);
    return record;
}
export function addDecisionRecord(cwd, input) {
    const record = compact({
        id: nextId('decision'),
        kind: 'decision',
        createdAt: new Date().toISOString(),
        summary: input.summary,
        taskIds: input.taskIds ?? [],
        owner: profileOwner(input.profile),
        rationale: input.rationale,
        outcome: input.outcome,
        alternatives: input.alternatives,
        evidenceIds: input.evidenceIds,
    });
    appendRecord(cwd, record);
    return record;
}
export function addHandoffRecord(cwd, input) {
    const record = compact({
        id: nextId('handoff'),
        kind: 'handoff',
        createdAt: new Date().toISOString(),
        summary: input.summary,
        taskIds: input.taskIds ?? [],
        from: profileOwner(input.from),
        to: profileOwner(input.to),
        changedFiles: input.changedFiles,
        risks: input.risks,
        nextActions: input.nextActions,
        acceptanceCriteria: input.acceptanceCriteria,
        capabilitySignals: input.capabilitySignals,
        evidenceIds: input.evidenceIds,
    });
    appendRecord(cwd, record);
    return record;
}
export function requestReview(cwd, input) {
    const record = compact({
        id: nextId('review'),
        kind: 'review',
        status: 'pending',
        createdAt: new Date().toISOString(),
        summary: input.summary,
        taskIds: input.taskIds ?? [],
        requester: profileOwner(input.requester),
        reviewer: input.reviewer ? profileOwner(input.reviewer) : undefined,
        gates: input.gates ?? [],
        evidenceIds: input.evidenceIds,
    });
    appendRecord(cwd, record);
    return record;
}
export function completeReview(cwd, input) {
    const existing = listRecords(cwd, 'review').find((r) => r.id === input.id);
    if (!existing)
        return err({ code: 'review-not-found', message: `Review not found: ${input.id}` });
    const isCorrection = input.result === 'blocked' || input.result === 'changes';
    const record = compact({
        ...existing,
        status: input.result,
        reviewer: input.reviewer ? profileOwner(input.reviewer) : existing.reviewer,
        findings: input.findings,
        recommendation: input.recommendation,
        completedAt: new Date().toISOString(),
        returnTarget: isCorrection ? input.returnTarget : undefined,
        correctionIteration: isCorrection ? (existing.correctionIteration ?? 0) + 1 : existing.correctionIteration,
    });
    appendRecord(cwd, record);
    return ok(record);
}
export function listRecords(cwd, kind) {
    return readJsonlFile(recordPath(cwd, kind));
}
export function recordPath(cwd, kind) {
    return join(cwd, '.setup-agents', 'state', RECORD_FILES[kind]);
}
export function profileOwner(profile) {
    return profile.startsWith('setup-agents:')
        ? profile
        : `setup-agents:${profile}`;
}
function appendRecord(cwd, record) {
    appendJsonlFile(recordPath(cwd, record.kind), record);
}
function cryptoSlug(len = 6) {
    return randomBytes(len).toString('hex').slice(0, len);
}
function nextId(kind) {
    return `setup-agents-${kind}-${Date.now()}-${cryptoSlug()}`;
}
const RECORD_ID_PATTERN = /^setup-agents-(evidence|decision|handoff|review)-\d{13,}-[a-f0-9]{6}$/;
export function generateRecordId(kind) {
    return nextId(kind);
}
export function isValidRecordId(id) {
    return RECORD_ID_PATTERN.test(id);
}
//# sourceMappingURL=orchestration-records.js.map