/*
 * 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, readJsonlFile } from './file-writer.js';
export const EFFORT_FILE = 'effort-estimates.jsonl';
export function effortPath(cwd) {
    return join(cwd, '.setup-agents', 'state', EFFORT_FILE);
}
export function addEffortEstimate(cwd, input) {
    const record = {
        id: `effort-${Date.now()}-${randomBytes(4).toString('hex')}`,
        storyId: input.storyId,
        phase: input.phase,
        workMode: input.workMode,
        actualMinutes: input.actualMinutes ?? null,
        estimatedUnguidedMinutes: input.estimatedUnguidedMinutes ?? null,
        confidence: input.confidence,
        rationale: input.rationale,
        createdAt: new Date().toISOString(),
        ...(input.tokenCost ? { tokenCost: input.tokenCost } : {}),
    };
    appendJsonlFile(effortPath(cwd), record);
    return record;
}
export function listEffortEstimates(cwd, storyId) {
    const all = readJsonlFile(effortPath(cwd));
    return storyId ? all.filter((r) => r.storyId === storyId) : all;
}
export function summarizeEffort(records, storyId) {
    const MODES = [
        'ai_autonomous',
        'ai_supervised',
        'ai_calibration_baseline',
        'human_manual',
        'human_review',
    ];
    const byMode = Object.fromEntries(MODES.map((m) => [m, 0]));
    let totalMinutes = 0;
    for (const r of records) {
        const mins = r.actualMinutes ?? 0;
        byMode[r.workMode] = (byMode[r.workMode] ?? 0) + mins;
        totalMinutes += mins;
    }
    const aiMinutes = (byMode.ai_autonomous ?? 0) + (byMode.ai_supervised ?? 0);
    const autonomyPct = totalMinutes > 0 ? Math.round((aiMinutes / totalMinutes) * 100) : null;
    const tokenCost = summarizeTokenCost(records);
    const unguidedTotal = records.reduce((sum, r) => sum + (r.estimatedUnguidedMinutes ?? 0), 0);
    const rulesMultiplier = unguidedTotal > 0 && totalMinutes > 0 ? Math.round((unguidedTotal / totalMinutes) * 100) / 100 : null;
    return { storyId, byMode, totalMinutes, autonomyPct, rulesMultiplier, tokenCost };
}
function summarizeTokenCost(records) {
    const costed = records.filter((r) => r.tokenCost !== undefined);
    if (costed.length === 0)
        return null;
    let totalCostUsd = 0;
    const byMode = {};
    const byStory = {};
    for (const r of costed) {
        // costed filter above guarantees tokenCost is defined
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const cost = r.tokenCost.costUsd;
        totalCostUsd += cost;
        const modeEntry = byMode[r.workMode] ?? { costUsd: 0, phases: 0 };
        modeEntry.costUsd += cost;
        modeEntry.phases += 1;
        byMode[r.workMode] = modeEntry;
        byStory[r.storyId] = (byStory[r.storyId] ?? 0) + cost;
    }
    return {
        totalCostUsd: Math.round(totalCostUsd * 10_000) / 10_000,
        byMode,
        byStory: Object.fromEntries(Object.entries(byStory).map(([k, v]) => [k, Math.round(v * 10_000) / 10_000])),
    };
}
//# sourceMappingURL=workflow-effort.js.map