#!/usr/bin/env node
"use strict";
/**
 * CLI Brain OpenCode Init Command
 * One-command setup for OpenCode integration
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const program = new commander_1.Command();
program
    .name("cli-brain-opencode")
    .description("CLI Brain OpenCode Integration")
    .version("1.0.0");
program
    .command("init")
    .description("Initialize CLI Brain in current project")
    .option("--nvidia-api-key <key>", "NVIDIA API key")
    .option("--default-model <model>", "Default model", "nvidia/moonshotai/kimi-k2.5")
    .option("--global", "Install agents globally (recommended)", true)
    .option("--local", "Copy agents to current project")
    .action(async (options) => {
    console.log("🧠 CLI Brain OpenCode Integration\n");
    try {
        // Step 1: Ensure global package installed
        await ensureGlobalInstall();
        // Step 2: Get NVIDIA API key
        const apiKey = await getNvidiaApiKey(options);
        // Step 3: Interactive configuration
        const config = await configureInteractively({
            apiKey,
            defaultModel: options.defaultModel
        });
        // Step 4: Save global config
        await saveGlobalConfig(config);
        // Step 5: Create plugin file in current project
        await createPluginFile(process.cwd());
        // Step 6: Create .env.example
        await createEnvExample(process.cwd());
        // Step 7: Test connection
        await testConnection(config);
        console.log("\n✅ Initialization complete!\n");
        console.log("🚀 Next steps:");
        console.log("  1. Run: opencode");
        console.log("  2. Try: > build a landing page");
        console.log("  3. Try: > @frontend-developer create navbar");
        console.log("  4. Try: > run workflow saas-mvp --name MyApp");
        console.log("\n📚 Documentation:");
        console.log("  - Agent list: opencode > list_agents");
        console.log("  - Available models: opencode > list_models");
        console.log("  - Workflow status: opencode > workflow_status WF-xxx");
    }
    catch (error) {
        console.error("\n❌ Initialization failed:", error instanceof Error ? error.message : error);
        process.exit(1);
    }
});
program
    .command("config")
    .description("Configure CLI Brain settings")
    .option("--api-key <key>", "Update NVIDIA API key")
    .option("--default-model <model>", "Update default model")
    .option("--show", "Show current config")
    .action(async (options) => {
    const configPath = path.join(os.homedir(), ".cli-brain", "config.json");
    if (options.show) {
        if (!fs.existsSync(configPath)) {
            console.log("No config found. Run: npx cli-brain-opencode init");
            return;
        }
        const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
        console.log("\n⚙️  Current Config:\n");
        console.log(JSON.stringify(config, null, 2));
        return;
    }
    let config = {};
    if (fs.existsSync(configPath)) {
        config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
    }
    if (options.apiKey) {
        config.nvidia = config.nvidia || {};
        config.nvidia.apiKey = options.apiKey;
    }
    if (options.defaultModel) {
        config.nvidia = config.nvidia || {};
        config.nvidia.defaultModel = options.defaultModel;
    }
    fs.mkdirSync(path.dirname(configPath), { recursive: true });
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    console.log("✅ Config updated!");
});
program
    .command("update")
    .description("Update agents to latest version")
    .action(async () => {
    console.log("📦 Updating CLI Brain...\n");
    try {
        // Re-install global package
        (0, child_process_1.execSync)("npm install -g cli-brain-opencode@latest", { stdio: "inherit" });
        console.log("\n✅ Updated to latest version!");
    }
    catch (error) {
        console.error("❌ Update failed:", error);
        process.exit(1);
    }
});
async function ensureGlobalInstall() {
    console.log("📦 Checking global installation...\n");
    try {
        // Check if already installed globally
        (0, child_process_1.execSync)("npm list -g cli-brain-opencode", { stdio: "ignore" });
        console.log("✅ Global package found\n");
    }
    catch {
        console.log("📥 Installing globally...\n");
        (0, child_process_1.execSync)("npm install -g cli-brain-opencode", { stdio: "inherit" });
        console.log("✅ Global package installed\n");
    }
}
async function getNvidiaApiKey(options) {
    // Priority: CLI option > env var > prompt
    if (options.nvidiaApiKey) {
        return options.nvidiaApiKey;
    }
    if (process.env.NVIDIA_API_KEY) {
        console.log("✅ Found NVIDIA_API_KEY in environment\n");
        return process.env.NVIDIA_API_KEY;
    }
    // Check existing config
    const configPath = path.join(os.homedir(), ".cli-brain", "config.json");
    if (fs.existsSync(configPath)) {
        const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
        if (config.nvidia?.apiKey) {
            console.log("✅ Found existing NVIDIA API key\n");
            return config.nvidia.apiKey;
        }
    }
    // Prompt user
    console.log("🔑 NVIDIA API Key required");
    console.log("   Get one at: https://build.nvidia.com/explore\n");
    // In real implementation, use inquirer or similar
    console.log("Please set NVIDIA_API_KEY environment variable or use --nvidia-api-key flag\n");
    throw new Error("NVIDIA API key required");
}
async function configureInteractively(options) {
    console.log("⚙️  Configuration\n");
    const availableModels = [
        { id: "nvidia/moonshotai/kimi-k2.5", name: "Kimi K2.5", desc: "Long context, excellent for coding" },
        { id: "nvidia/google/gemma-4-31b-it", name: "Gemma 4 31B", desc: "Balanced performance and efficiency" },
        { id: "nvidia/deepseek-ai/deepseek-r1", name: "DeepSeek R1", desc: "Strong reasoning, chain-of-thought" },
        { id: "nvidia/mistralai/mixtral-8x22b-instruct-v0.1", name: "Mixtral 8x22B", desc: "MoE architecture, efficient" }
    ];
    console.log("Available models:");
    availableModels.forEach((m, i) => {
        const selected = m.id === options.defaultModel ? " (default)" : "";
        console.log(`  ${i + 1}. ${m.name}${selected}`);
        console.log(`     ${m.desc}`);
    });
    console.log();
    return {
        nvidia: {
            apiKey: options.apiKey,
            baseUrl: "https://integrate.api.nvidia.com/v1",
            defaultModel: options.defaultModel,
            availableModels: availableModels.map(m => m.id)
        },
        agents: {
            path: path.join(os.homedir(), ".cli-brain", "agents")
        }
    };
}
async function saveGlobalConfig(config) {
    console.log("💾 Saving configuration...\n");
    const cliBrainDir = path.join(os.homedir(), ".cli-brain");
    fs.mkdirSync(cliBrainDir, { recursive: true });
    // Save config
    const configPath = path.join(cliBrainDir, "config.json");
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    // Copy agents to global directory
    const globalAgentsPath = path.join(cliBrainDir, "agents");
    const sourceAgentsPath = path.join(__dirname, "..", "..", "agents");
    if (fs.existsSync(sourceAgentsPath) && !fs.existsSync(globalAgentsPath)) {
        console.log("📦 Copying agents to global directory...\n");
        copyDirectory(sourceAgentsPath, globalAgentsPath);
    }
    console.log(`✅ Config saved to: ${configPath}\n`);
}
async function createPluginFile(projectPath) {
    console.log("🔌 Creating OpenCode plugin...\n");
    const opencodeDir = path.join(projectPath, ".opencode");
    fs.mkdirSync(opencodeDir, { recursive: true });
    // Create plugin loader file
    const pluginContent = `// CLI Brain OpenCode Plugin Loader
// This file loads the global CLI Brain plugin

const path = require('path');
const os = require('os');

module.exports = async function(ctx) {
  // Load from global installation
  const globalPath = path.join(os.homedir(), '.cli-brain');
  const pluginPath = path.join(globalPath, 'node_modules', 'cli-brain-opencode', 'dist', 'opencode', 'plugin.js');
  
  // Check for local override
  const localPluginPath = path.join(ctx.worktree, '.opencode', 'cli-brain-override.js');
  
  if (require('fs').existsSync(localPluginPath)) {
    // Use local override
    const localPlugin = require(localPluginPath);
    return localPlugin(ctx);
  }
  
  if (require('fs').existsSync(pluginPath)) {
    // Use global plugin
    const plugin = require(pluginPath);
    return plugin.default(ctx);
  }
  
  // Not installed
  return {
    tool: {
      cli_brain_status: {
        description: "CLI Brain status",
        args: {},
        execute: async () => {
          return "CLI Brain not installed. Run: npx cli-brain-opencode init";
        }
      }
    }
  };
};
`;
    const pluginPath = path.join(opencodeDir, "opencode-plugin.js");
    fs.writeFileSync(pluginPath, pluginContent);
    console.log(`✅ Plugin created: ${pluginPath}\n`);
}
async function createEnvExample(projectPath) {
    const envContent = `# CLI Brain OpenCode Configuration
# Copy this file to .env and add your values

# Required: NVIDIA API Key
# Get from: https://build.nvidia.com/explore
NVIDIA_API_KEY=nvapi-your-key-here

# Optional: Override default model
# Options: nvidia/moonshotai/kimi-k2.5, nvidia/google/gemma-4-31b-it, etc
# NVIDIA_DEFAULT_MODEL=nvidia/moonshotai/kimi-k2.5
`;
    const envPath = path.join(projectPath, ".env.example");
    fs.writeFileSync(envPath, envContent);
    console.log(`✅ Environment template: ${envPath}\n`);
}
async function testConnection(config) {
    console.log("🧪 Testing NVIDIA API connection...\n");
    try {
        const response = await fetch(`${config.nvidia.baseUrl}/models`, {
            headers: {
                "Authorization": `Bearer ${config.nvidia.apiKey}`
            }
        });
        if (response.ok) {
            console.log("✅ NVIDIA API connection successful!\n");
        }
        else {
            console.log("⚠️  Warning: Could not verify NVIDIA API connection\n");
        }
    }
    catch {
        console.log("⚠️  Warning: Could not test connection (network issue)\n");
    }
}
function copyDirectory(src, dest) {
    fs.mkdirSync(dest, { recursive: true });
    const entries = fs.readdirSync(src, { withFileTypes: true });
    for (const entry of entries) {
        const srcPath = path.join(src, entry.name);
        const destPath = path.join(dest, entry.name);
        if (entry.isDirectory()) {
            copyDirectory(srcPath, destPath);
        }
        else {
            fs.copyFileSync(srcPath, destPath);
        }
    }
}
program.parse();
//# sourceMappingURL=init.js.map