import { Timer } from './Timer.js';
import { DebugLlmReq } from './DebugLlmReq.js';
import { PriorityContainer } from '../agent-core/index.js';
export class DebugLog {
    workspace;
    goal = {
        prompt: '',
        time: new Timer(),
        tokens: 0,
        llmReqs: 0,
    };
    steps = [];
    longestLlmReqs;
    constructor(workspace) {
        this.workspace = workspace;
        this.longestLlmReqs = new PriorityContainer(5, (a, b) => b.time.duration() - a.time.duration());
    }
    get latestStep() {
        return this.steps[this.steps.length - 1];
    }
    async save() {
        await this.workspace.writeFile('debug.json', this.toString());
        await this.workspace.writeFile('perf.json', JSON.stringify(this.longestLlmReqs.getItems(), null, 2));
    }
    async goalStart(prompt) {
        this.goal.prompt = prompt;
        this.goal.time.start();
        await this.save();
    }
    async goalEnd() {
        this.goal.time.end();
        await this.save();
    }
    async stepStart() {
        const step = {
            time: new Timer(),
            llmTime: new Timer(),
            llmReqs: [],
        };
        step.time.start();
        this.steps.push(step);
        await this.save();
    }
    async stepEnd() {
        this.latestStep.time.end();
        await this.save();
    }
    async stepLog(message) {
        this.latestStep.message = message;
        await this.save();
    }
    async stepError(error) {
        this.latestStep.error = error;
        await this.save();
    }
    async stepLlmReq(time, chatLogs, response) {
        const req = new DebugLlmReq(time, chatLogs, response);
        this.goal.llmReqs += 1;
        this.goal.tokens += req.tokens;
        this.latestStep.llmReqs.push(req);
        this.latestStep.llmTime.add(req.time.duration());
        this.longestLlmReqs.addItem(req);
        await this.save();
    }
    toString() {
        return JSON.stringify(this.toJSON(), null, 2);
    }
    toJSON() {
        return {
            goal: this.goal,
            steps: this.steps,
        };
    }
}
