/// <reference types="vscode" />
// @ts-check
// API: https://code.visualstudio.com/api/references/vscode-api
// @ts-ignore
const vscode = require('vscode');
 * @typedef {import('vscode').ExtensionContext} ExtensionContext
 * @typedef {import('vscode').commands} commands
 * @typedef {import('vscode').window} window
 * @typedef {import('vscode').TextEditor} TextEditor
 * @typedef {import('vscode').TextDocument} TextDocument
 */

/**
 * Aktiviert die Erweiterung und registriert den Auto-Resume-Befehl
 * @param {vscode.ExtensionContext} context - Der Erweiterungskontext
 */
function activate(context) {
    const disposable = vscode.commands.registerCommand('extension.autoResume', () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) return;

        const document = editor.document;
        const text = document.getText();
        
        // Track last click time to avoid multiple clicks
        let lastClickTime = 0;
        
        // Main function that looks for and clicks the resume link
        function clickResumeLink() {
            // Prevent clicking too frequently (3 second cooldown)
            const now = Date.now();
            if (now - lastClickTime < 3000) return;
            
            // Check if text contains rate limit text
            if (text.includes('stop the agent after 25 tool calls') || 
                text.includes('Note: we default stop')) {
                
                // Find the resume link position
                const resumePos = text.indexOf('resume the conversation');
                if (resumePos !== -1) {
                    vscode.window.showInformationMessage('Auto-resuming conversation...');
                    lastClickTime = now;
                }
            }
        }
        
        // Führe periodisch aus
        const interval = global.setInterval(clickResumeLink, 1000);
        
        // Speichere das Intervall in den Subscriptions
        context.subscriptions.push({
            dispose: () => global.clearInterval(interval)
        });
        // Führe die Funktion sofort aus
        clickResumeLink();
    });

    context.subscriptions.push(disposable);
}

function deactivate() {
    // Cleanup if needed
}

module.exports = {
    activate,
    deactivate
}
