/**
 * Local Model Setup - Integrated Installation
 * Automatically installs Ollama and downloads models when needed
 * Makes it feel like one unified system
 */
import * as os from 'os';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
/**
 * Check if Ollama is installed and running
 */
export async function checkOllamaInstallation() {
    try {
        // Check if ollama command exists
        const { stdout } = await execAsync('ollama --version');
        const ollamaPath = stdout.trim();
        // Check if Ollama server is running
        try {
            const response = await fetch('http://localhost:11434/api/tags');
            if (response.ok) {
                const data = await response.json();
                const models = (data.models || []).map((m) => m.name);
                return {
                    success: true,
                    message: 'Ollama is installed and running',
                    ollamaInstalled: true,
                    ollamaPath,
                    modelsAvailable: models,
                };
            }
        }
        catch (e) {
            // Server not running, but Ollama is installed
            return {
                success: false,
                message: 'Ollama is installed but server is not running',
                ollamaInstalled: true,
                ollamaPath,
            };
        }
    }
    catch (error) {
        return {
            success: false,
            message: 'Ollama is not installed',
            ollamaInstalled: false,
        };
    }
    return {
        success: false,
        message: 'Ollama status unknown',
        ollamaInstalled: false,
    };
}
/**
 * Install Ollama automatically
 * For Windows: Opens download page and provides instructions
 * For Mac/Linux: Uses package managers
 */
export async function installOllama() {
    const platform = os.platform();
    if (platform === 'win32') {
        // Windows - open download page and provide instructions
        try {
            // Try to open the download page
            const { exec } = await import('child_process');
            exec('start https://ollama.com/download/windows');
            return {
                success: false, // Not fully automatic on Windows
                message: 'Please download and install Ollama from the opened page, then restart this terminal.',
            };
        }
        catch (error) {
            return {
                success: false,
                message: 'Please download Ollama from https://ollama.ai/download and install it, then restart this terminal.',
            };
        }
    }
    else if (platform === 'darwin') {
        // macOS - use Homebrew or direct download
        try {
            // Try Homebrew first
            await execAsync('brew install ollama');
            return {
                success: true,
                message: 'Ollama installed via Homebrew',
            };
        }
        catch (e) {
            return {
                success: false,
                message: 'Please install Ollama manually: brew install ollama or download from https://ollama.ai',
            };
        }
    }
    else {
        // Linux
        try {
            await execAsync('curl -fsSL https://ollama.com/install.sh | sh');
            return {
                success: true,
                message: 'Ollama installed successfully',
            };
        }
        catch (error) {
            return {
                success: false,
                message: `Installation failed: ${error.message}. Please install manually from https://ollama.ai`,
            };
        }
    }
}
/**
 * Start Ollama server if not running
 */
export async function startOllamaServer() {
    try {
        // Check if already running
        const response = await fetch('http://localhost:11434/api/tags');
        if (response.ok) {
            return {
                success: true,
                message: 'Ollama server is already running',
            };
        }
    }
    catch (e) {
        // Server not running, start it
    }
    try {
        const platform = os.platform();
        if (platform === 'win32') {
            // On Windows, Ollama runs as a service, so we just need to start it
            await execAsync('ollama serve', { timeout: 5000 });
        }
        else {
            // On Unix, start in background
            await execAsync('ollama serve &');
        }
        // Wait for server to start
        for (let i = 0; i < 10; i++) {
            await new Promise(resolve => setTimeout(resolve, 1000));
            try {
                const response = await fetch('http://localhost:11434/api/tags');
                if (response.ok) {
                    return {
                        success: true,
                        message: 'Ollama server started successfully',
                    };
                }
            }
            catch (e) {
                // Keep waiting
            }
        }
        return {
            success: false,
            message: 'Ollama server failed to start. Please start it manually: ollama serve',
        };
    }
    catch (error) {
        return {
            success: false,
            message: `Failed to start Ollama server: ${error.message}`,
        };
    }
}
/**
 * Download a model using Ollama API
 */
export async function downloadModel(modelName) {
    try {
        // Verify Ollama is running
        const check = await checkOllamaInstallation();
        if (!check.ollamaInstalled) {
            return {
                success: false,
                message: 'Ollama is not installed. Please install it first.',
            };
        }
        // Start server if not running
        await startOllamaServer();
        // Use Ollama's pull command (this handles downloading)
        console.log(`Downloading model: ${modelName}...`);
        console.log('This may take several minutes depending on model size...');
        // Use ollama pull command
        const { stdout, stderr } = await execAsync(`ollama pull ${modelName}`, {
            maxBuffer: 10 * 1024 * 1024, // 10MB buffer for output
        });
        // Verify model was downloaded
        const verifyResponse = await fetch('http://localhost:11434/api/tags');
        if (verifyResponse.ok) {
            const data = await verifyResponse.json();
            const models = (data.models || []).map((m) => m.name);
            if (models.includes(modelName)) {
                return {
                    success: true,
                    message: `Model '${modelName}' downloaded successfully`,
                };
            }
        }
        return {
            success: false,
            message: `Model download completed but verification failed. Check: ollama list`,
        };
    }
    catch (error) {
        return {
            success: false,
            message: `Failed to download model: ${error.message}`,
        };
    }
}
/**
 * Verify execution is truly local (proof it's not going through gateway)
 */
export async function verifyLocalExecution() {
    const startTime = Date.now();
    try {
        // Make a test call to local Ollama
        const response = await fetch('http://localhost:11434/api/generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                model: 'llama2',
                prompt: 'test',
                stream: false,
            }),
        });
        const responseTime = Date.now() - startTime;
        const isLocal = response.ok && responseTime < 5000; // Local should be fast
        return {
            isLocal,
            proof: {
                networkCheck: true, // We're calling localhost, not external
                executionPath: 'localhost:11434 (direct)',
                responseTime,
            },
        };
    }
    catch (error) {
        return {
            isLocal: false,
            proof: {
                networkCheck: false,
                executionPath: 'unknown',
                responseTime: Date.now() - startTime,
            },
        };
    }
}
//# sourceMappingURL=local-setup.js.map