"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentSyncKnowhowWeb = void 0;
const KnowhowClient_1 = require("./KnowhowClient");
class AgentSyncKnowhowWeb {
    client;
    baseUrl;
    knowhowTaskId;
    eventHandlersSetup = false;
    finalizationPromise = null;
    agent;
    threadUpdateHandler;
    doneHandler;
    pendingThreadUpdatePromise = null;
    constructor(baseUrl = KnowhowClient_1.KNOWHOW_API_URL) {
        this.baseUrl = baseUrl;
        this.client = new KnowhowClient_1.KnowhowSimpleClient(baseUrl);
    }
    async createChatTask(options) {
        if (!options.messageId || !this.baseUrl) {
            return undefined;
        }
        try {
            console.log(`Base URL for Knowhow API: ${this.baseUrl}, Message ID: ${options.messageId}`);
            const response = await this.client.createChatTask({
                messageId: options.messageId,
                prompt: options.prompt,
            });
            const knowhowTaskId = response.data.id;
            console.log(`✅ Created Knowhow chat task: ${knowhowTaskId}`);
            return knowhowTaskId;
        }
        catch (error) {
            console.error(`❌ Failed to create Knowhow chat task:`, error);
            return undefined;
        }
    }
    async updateChatTask(knowhowTaskId, agent, inProgress, result) {
        if (!knowhowTaskId || !this.baseUrl) {
            return;
        }
        try {
            await this.client.updateChatTask(knowhowTaskId, {
                threads: agent.getThreads(),
                totalCostUsd: agent.getTotalCostUsd(),
                inProgress,
                ...(result ? { result } : {}),
            });
            console.log(`✅ Updated Knowhow chat task: ${knowhowTaskId}`);
        }
        catch (error) {
            console.error(`❌ Failed to update Knowhow chat task:`, error);
        }
    }
    async checkAndProcessPendingMessages(agent, knowhowTaskId) {
        if (!knowhowTaskId || !this.baseUrl) {
            return;
        }
        try {
            const taskDetailsResponse = await this.client.getTaskDetails(knowhowTaskId);
            const taskDetails = taskDetailsResponse.data;
            if (taskDetails.status === "killed") {
                console.log(`🛑 Agent task ${knowhowTaskId} was killed via API`);
                await agent.kill();
                return;
            }
            if (taskDetails.status === "paused") {
                console.log(`⏸️ Agent task ${knowhowTaskId} is paused, waiting for resume...`);
                await agent.pause();
                await this.waitForResume(agent, knowhowTaskId);
                return;
            }
            const pendingResponse = await this.client.getPendingMessages(knowhowTaskId);
            const pendingMessages = pendingResponse.data || [];
            if (pendingMessages.length === 0) {
                return;
            }
            console.log(`📬 Processing ${pendingMessages.length} pending message(s) for task ${knowhowTaskId}`);
            const messageIds = [];
            for (const msg of pendingMessages) {
                agent.addPendingUserMessage({
                    role: msg.role,
                    content: msg.message,
                });
                messageIds.push(msg.id);
            }
            await this.client.markMessagesAsProcessed(knowhowTaskId, messageIds);
            console.log(`✅ Marked ${messageIds.length} message(s) as processed`);
        }
        catch (error) {
            console.error(`❌ Error checking/processing pending messages:`, error);
        }
    }
    async waitForResume(agent, knowhowTaskId) {
        const POLL_INTERVAL_MS = 2000;
        const MAX_WAIT_MS = 60 * 60 * 1000;
        const startTime = Date.now();
        while (Date.now() - startTime < MAX_WAIT_MS) {
            await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
            try {
                const taskDetailsResponse = await this.client.getTaskDetails(knowhowTaskId);
                const taskDetails = taskDetailsResponse.data;
                if (taskDetails.status === "killed") {
                    console.log(`🛑 Agent task ${knowhowTaskId} was killed while paused`);
                    await agent.kill();
                    return;
                }
                if (taskDetails.status === "running" ||
                    taskDetails.status === "completed") {
                    console.log(`▶️ Agent task ${knowhowTaskId} resumed`);
                    await agent.unpause();
                    return;
                }
            }
            catch (error) {
                console.error(`❌ Error polling task status:`, error);
            }
        }
        console.warn(`⚠️ Timeout waiting for resume on task ${knowhowTaskId}`);
    }
    async setupAgentSync(agent, knowhowTaskId) {
        if (!knowhowTaskId || !this.baseUrl) {
            return;
        }
        this.knowhowTaskId = knowhowTaskId;
        if (!this.eventHandlersSetup) {
            this.setupEventHandlers(agent);
            this.eventHandlersSetup = true;
        }
    }
    setupEventHandlers(agent) {
        this.agent = agent;
        this.threadUpdateHandler = async () => {
            if (!this.knowhowTaskId || !this.baseUrl) {
                return;
            }
            try {
                this.pendingThreadUpdatePromise = (async () => {
                    await this.updateChatTask(this.knowhowTaskId, agent, true);
                    await this.checkAndProcessPendingMessages(agent, this.knowhowTaskId);
                })();
                await this.pendingThreadUpdatePromise;
            }
            catch (error) {
                console.error(`❌ Error during threadUpdate sync:`, error);
            }
        };
        agent.agentEvents.on(agent.eventTypes.threadUpdate, this.threadUpdateHandler);
        this.doneHandler = async (result) => {
            if (!this.knowhowTaskId || !this.baseUrl) {
                console.warn(`⚠️ [AgentSync] Cannot finalize: knowhowTaskId=${this.knowhowTaskId}, baseUrl=${this.baseUrl}`);
                return;
            }
            console.log(`🎯 [AgentSync] Done event received for task: ${this.knowhowTaskId}`);
            this.finalizationPromise = (async () => {
                try {
                    if (this.pendingThreadUpdatePromise) {
                        console.log(`⏳ [AgentSync] Awaiting pending thread update before finalizing...`);
                        await this.pendingThreadUpdatePromise.catch(() => {
                        });
                        this.pendingThreadUpdatePromise = null;
                    }
                    console.log(`Updating Knowhow chat task on completion..., ${this.knowhowTaskId}`);
                    await this.updateChatTask(this.knowhowTaskId, agent, false, result);
                    console.log(`✅ Completed Knowhow chat task: ${this.knowhowTaskId}`);
                }
                catch (error) {
                    console.error(`❌ Error finalizing task:`, error);
                    throw error;
                }
            })();
        };
        agent.agentEvents.on(agent.eventTypes.done, this.doneHandler);
    }
    async waitForFinalization() {
        if (this.finalizationPromise) {
            await this.finalizationPromise;
        }
    }
    reset() {
        if (this.agent) {
            if (this.threadUpdateHandler) {
                this.agent.agentEvents.removeListener(this.agent.eventTypes.threadUpdate, this.threadUpdateHandler);
                this.threadUpdateHandler = undefined;
            }
            if (this.doneHandler) {
                this.agent.agentEvents.removeListener(this.agent.eventTypes.done, this.doneHandler);
                this.doneHandler = undefined;
            }
            this.agent = undefined;
        }
        this.knowhowTaskId = undefined;
        this.eventHandlersSetup = false;
        this.finalizationPromise = null;
        this.pendingThreadUpdatePromise = null;
    }
    async finalizeTask(agent, knowhowTaskId, result) {
        if (knowhowTaskId && this.baseUrl) {
            console.log(`Updating Knowhow chat task on completion..., ${knowhowTaskId}`);
            await this.updateChatTask(knowhowTaskId, agent, false, result);
            console.log(`✅ Completed Knowhow chat task: ${knowhowTaskId}`);
        }
    }
}
exports.AgentSyncKnowhowWeb = AgentSyncKnowhowWeb;
//# sourceMappingURL=AgentSyncKnowhowWeb.js.map