"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoteSyncModule = void 0;
const BaseChatModule_1 = require("./BaseChatModule");
const KnowhowClient_1 = require("../../services/KnowhowClient");
const AgentSyncKnowhowWeb_1 = require("../../services/AgentSyncKnowhowWeb");
const config_1 = require("../../config");
class RemoteSyncModule extends BaseChatModule_1.BaseChatModule {
    name = "remote-sync";
    description = "Remote sync functionality (/sync:remote, /sync:status)";
    remoteSessionId;
    workerId;
    autoSync = false;
    syncedMessageCount = 0;
    agentModule;
    client;
    constructor(agentModule) {
        super();
        this.agentModule = agentModule;
        this.client = new KnowhowClient_1.KnowhowSimpleClient(KnowhowClient_1.KNOWHOW_API_URL);
    }
    async initialize(service) {
        await super.initialize(service);
        const config = await (0, config_1.getConfig)();
        if (config.syncRemote === true) {
            this.autoSync = true;
            console.log("📡 Remote auto-sync enabled (from config syncRemote: true)");
        }
        if (config.worker?.workerId) {
            this.workerId = config.worker.workerId;
            console.log(`🔗 Worker ID loaded: ${this.workerId}`);
        }
    }
    getCommands() {
        return [
            {
                name: "sync:remote",
                description: "Push the current agent task to the remote KnowHow app. Creates a remote session+message if needed.",
                handler: this.handleSyncRemote.bind(this),
            },
            {
                name: "share",
                description: "Alias for /sync:remote",
                handler: this.handleSyncRemote.bind(this),
            },
            {
                name: "sync:remote:on",
                description: "Enable remote auto-sync for all future agent tasks and save to config",
                handler: this.handleSyncRemoteOn.bind(this),
            },
            {
                name: "sync:remote:off",
                description: "Disable auto remote sync for future tasks",
                handler: this.handleSyncRemoteOff.bind(this),
            },
            {
                name: "sync:status",
                description: "Show current remote sync state",
                handler: this.handleSyncStatus.bind(this),
            },
        ];
    }
    getActiveTask(taskIdArg) {
        const registry = this.agentModule.getTaskRegistry();
        const context = this.chatService?.getContext();
        if (taskIdArg) {
            const taskInfo = registry.get(taskIdArg);
            if (taskInfo)
                return { taskId: taskIdArg, taskInfo };
            console.log(`⚠️  Task "${taskIdArg}" not found in registry.`);
            return undefined;
        }
        const activeId = context?.activeAgentTaskId;
        if (activeId) {
            const taskInfo = registry.get(activeId);
            if (taskInfo)
                return { taskId: activeId, taskInfo };
        }
        const allTasks = registry.getEntries();
        if (allTasks.length > 0) {
            const [taskId, taskInfo] = allTasks[allTasks.length - 1];
            return { taskId, taskInfo };
        }
        return undefined;
    }
    extractSessionId(input) {
        const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
        const match = input.match(uuidRegex);
        if (match) {
            return match[0];
        }
        return undefined;
    }
    async ensureRemoteSession(title, prompt) {
        if (this.remoteSessionId) {
            console.log(`📡 Using existing remote session: ${this.remoteSessionId}`);
            return this.remoteSessionId;
        }
        console.log("📡 Creating remote session for this terminal session...");
        const result = await this.client.createSessionPlaceholder({
            title: title.slice(0, 80) || "CLI Session",
            workerId: this.workerId,
            metadata: { source: "cli", createdAt: new Date().toISOString() },
        });
        this.remoteSessionId = result.sessionId;
        console.log(`✅ Remote session created: ${result.sessionId}`);
        return result.sessionId;
    }
    async createRemoteMessagePlaceholder(sessionId, prompt, agentName, modelName) {
        const result = await this.client.createMessagePlaceholder(sessionId, {
            content: prompt,
            agentName,
            modelName,
            metadata: { source: "cli", createdAt: new Date().toISOString() },
        });
        return { messageId: result.messageId, taskId: result.taskId };
    }
    async handleSyncRemote(args) {
        const argRaw = args[0];
        if (argRaw) {
            const sessionId = this.extractSessionId(argRaw);
            if (sessionId) {
                this.remoteSessionId = sessionId;
                console.log(`📡 Using remote session: ${sessionId}`);
                console.log("   Future agent interactions will be appended to this session.\n" +
                    "   Use /sync:remote:off to disable, or /sync:remote:on to persist to config.");
                if (!this.autoSync) {
                    this.autoSync = true;
                }
                const taskEntry = this.getActiveTask(undefined);
                if (taskEntry) {
                    await this.syncTask(taskEntry.taskId);
                }
                return;
            }
        }
        const taskIdArg = argRaw;
        const taskEntry = this.getActiveTask(taskIdArg);
        if (!taskEntry) {
            this.autoSync = true;
            console.log("📡 Remote auto-sync enabled for this session.\n" +
                "   Future agent interactions will be pushed to the remote KnowHow app.\n" +
                "   Use /sync:remote:off to disable, or /sync:remote:on to persist to config.");
            return;
        }
        await this.syncTask(taskEntry.taskId);
        if (!this.autoSync) {
            this.autoSync = true;
            console.log("📡 Remote auto-sync enabled for future agent tasks this session.\n" +
                "   Use /sync:remote:on to persist this setting, or /sync:remote:off to disable.");
        }
    }
    async syncTask(taskId) {
        const registry = this.agentModule.getTaskRegistry();
        const taskInfo = registry.get(taskId);
        this.client.refreshJwt();
        if (!taskInfo) {
            console.log(`⚠️  Task "${taskId}" not found in registry.`);
            return;
        }
        if (taskInfo.knowhowTaskId && taskInfo.chatSessionId) {
            console.log(`ℹ️  Task "${taskId}" is already synced to remote session ${taskInfo.chatSessionId}.\n` +
                `   Remote task ID: ${taskInfo.knowhowTaskId}\n` +
                `   Use /sync:status to see full sync state.`);
            return;
        }
        try {
            console.log("\n🔐 Checking KnowHow API credentials...");
            const me = await this.client.me();
            console.log(`✅ Authenticated as ${me.data?.email || "unknown"}`);
            const title = taskInfo.initialInput?.slice(0, 80) || `CLI Session – ${new Date().toLocaleString()}`;
            const sessionId = await this.ensureRemoteSession(title, taskInfo.initialInput);
            console.log(`\n📨 Creating remote message for task: ${taskId}`);
            const agentName = taskInfo.agentName;
            const modelName = taskInfo.agent?.getModel();
            const { messageId, taskId: placeholderTaskId } = await this.createRemoteMessagePlaceholder(sessionId, taskInfo.formattedPrompt || taskInfo.initialInput, agentName, modelName);
            console.log(`✅ Remote message created: ${messageId}`);
            const knowhowTaskId = placeholderTaskId;
            if (!knowhowTaskId) {
                console.log("❌ Failed to create remote agent task. Aborting sync.");
                return;
            }
            console.log(`\n🔗 Using task from message placeholder: ${knowhowTaskId}`);
            const webSync = new AgentSyncKnowhowWeb_1.AgentSyncKnowhowWeb(KnowhowClient_1.KNOWHOW_API_URL);
            console.log(`✅ Remote task created: ${knowhowTaskId}`);
            taskInfo.knowhowMessageId = messageId;
            taskInfo.knowhowTaskId = knowhowTaskId;
            taskInfo.chatSessionId = sessionId;
            const sessionManager = this.agentModule.getSessionManager();
            sessionManager.updateSession(taskId, taskInfo, taskInfo.agent?.getThreads() || []);
            console.log(`\n🚀 Syncing thread progress to remote...`);
            const agent = taskInfo.agent;
            if (agent) {
                if (taskInfo.status === "completed" || taskInfo.status === "failed") {
                    await webSync.setupAgentSync(agent, knowhowTaskId);
                    await webSync.updateChatTask(knowhowTaskId, agent, false, "Synced from CLI");
                    console.log(`✅ Sync complete!`);
                }
                else {
                    await webSync.setupAgentSync(agent, knowhowTaskId);
                    console.log(`✅ Live sync attached! Thread updates will push as the agent runs.`);
                }
            }
            else {
                console.log("⚠️  Agent not found in task info; skipping live sync.");
            }
            this.syncedMessageCount++;
            const baseUrl = KnowhowClient_1.KNOWHOW_API_URL.replace("/api", "").replace("api.", "");
            console.log(`\n💾 Local session updated with remote IDs.\n` +
                `🌐 View your task at: ${baseUrl}/chat/${sessionId}`);
        }
        catch (error) {
            console.error(`❌ Remote sync failed: ${error?.message || error}\n` +
                `   Local state is unaffected. You can retry with /sync:remote.`);
        }
    }
    async handleSyncRemoteOff(_args) {
        this.autoSync = false;
        try {
            const config = await (0, config_1.getConfig)();
            await (0, config_1.updateConfig)({ ...config, syncRemote: false });
            console.log("💾 Config updated: syncRemote set to false");
        }
        catch (e) {
            console.log(`⚠️  Could not update config: ${e?.message}`);
        }
        console.log("🔕 Remote auto-sync disabled for future tasks.\n" +
            "   Existing synced tasks will continue to push updates.\n" +
            "   Use /sync:remote to manually sync a task.");
    }
    async handleSyncRemoteOn(_args) {
        this.autoSync = true;
        try {
            const config = await (0, config_1.getConfig)();
            await (0, config_1.updateConfig)({ ...config, syncRemote: true });
            console.log("💾 Config updated: syncRemote set to true");
        }
        catch (e) {
            console.log(`⚠️  Could not update config: ${e?.message}`);
        }
        console.log("📡 Remote auto-sync enabled for all future agent tasks.\n" +
            "   Every new agent interaction will be pushed to the remote KnowHow app.\n" +
            "   Use /sync:remote:off to disable.");
    }
    async handleSyncStatus(_args) {
        const lines = ["\n📊 Remote Sync Status"];
        lines.push("─".repeat(50));
        if (this.workerId) {
            lines.push(`🔧 Worker ID: ${this.workerId}`);
        }
        else {
            lines.push(`🔧 Worker ID: not set (start worker to register)`);
        }
        if (this.remoteSessionId) {
            lines.push(`✅ Remote session active: ${this.remoteSessionId}`);
        }
        else {
            lines.push("❌ No remote session (run /sync:remote to create one)");
        }
        lines.push(`🔄 Auto-sync: ${this.autoSync ? "enabled" : "disabled"}`);
        lines.push(`📨 Messages synced this session: ${this.syncedMessageCount}`);
        const registry = this.agentModule.getTaskRegistry();
        const syncedTasks = registry
            .getAll()
            .filter((t) => t.knowhowTaskId && t.chatSessionId);
        if (syncedTasks.length > 0) {
            lines.push("\nSynced tasks:");
            syncedTasks.forEach((t) => {
                lines.push(`  • ${t.taskId.slice(0, 40)} → ${t.knowhowTaskId} (${t.status})`);
            });
        }
        lines.push("─".repeat(50));
        console.log(lines.join("\n"));
    }
    isAutoSyncEnabled() {
        return this.autoSync;
    }
    getRemoteSessionId() {
        return this.remoteSessionId;
    }
}
exports.RemoteSyncModule = RemoteSyncModule;
//# sourceMappingURL=RemoteSyncModule.js.map