/*
 * 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 { appendJsonlFile, dedupeById, readJsonlFile } from './file-writer.js';
import { readWorkflowRun, updatePhaseStatus } from './workflow-engine.js';
export function clarificationPath(cwd) {
    return join(cwd, '.setup-agents', 'state', 'clarifications.jsonl');
}
export function openClarification(cwd, opts) {
    const run = readWorkflowRun(cwd, opts.runId);
    if (!run)
        throw new Error(`Workflow run not found: ${opts.runId}`);
    const activePhaseRecord = run.phases.find((p) => p.phase === opts.fromRole);
    if (!activePhaseRecord ||
        (activePhaseRecord.status !== 'running' && activePhaseRecord.status !== 'awaiting_clarification')) {
        throw new Error(`Phase '${opts.fromRole}' is not active in run ${opts.runId}. Only developer or qa phases in running status can open clarifications.`);
    }
    if (opts.fromRole !== 'developer' && opts.fromRole !== 'qa') {
        throw new Error(`Clarifications can only be opened from developer or qa phases. Got: ${opts.fromRole}`);
    }
    const now = new Date().toISOString();
    const record = {
        id: nextClarificationId(),
        runId: opts.runId,
        storyId: opts.storyId,
        fromRole: opts.fromRole,
        toRole: opts.toRole,
        question: opts.question,
        status: 'open',
        createdAt: now,
    };
    appendClarification(cwd, record);
    const updatedRun = updatePhaseStatus(cwd, run, opts.fromRole, 'awaiting_clarification', {
        clarificationIds: [record.id],
    });
    return { record, run: updatedRun };
}
export function answerClarification(cwd, id, answer) {
    const records = readClarifications(cwd);
    const idx = records.findLastIndex((r) => r.id === id);
    if (idx === -1)
        throw new Error(`Clarification not found: ${id}`);
    const existing = records[idx];
    if (existing.status === 'answered')
        throw new Error(`Clarification ${id} is already answered`);
    const now = new Date().toISOString();
    const updated = { ...existing, answer, status: 'answered', answeredAt: now };
    appendClarification(cwd, updated);
    const run = readWorkflowRun(cwd, existing.runId);
    if (!run)
        throw new Error(`Workflow run not found: ${existing.runId}`);
    const updatedRun = updatePhaseStatus(cwd, run, existing.fromRole, 'running');
    return { record: updated, run: updatedRun };
}
export function listClarifications(cwd, runId) {
    return dedupeById(readClarifications(cwd).filter((r) => r.runId === runId));
}
function readClarifications(cwd) {
    return readJsonlFile(clarificationPath(cwd));
}
function appendClarification(cwd, record) {
    appendJsonlFile(clarificationPath(cwd), record);
}
function nextClarificationId() {
    return `sa-clarification-${Date.now()}-${randomBytes(4).toString('hex')}`;
}
//# sourceMappingURL=clarification.js.map