#!/usr/bin/env node
'use strict';

/**
 * MCP Scan Skill — discovers tools from all Claude Code MCP servers
 * and caches them in the brain DB for fast lookup.
 *
 * Runs hourly. Results are stored in the `mcp_tools_cache` table
 * and used by the chat system prompt so Wall-E knows what it can do.
 */

const path = require('path');
const brain = require(path.resolve(__dirname, '../../..', 'brain'));
const mcpClient = require(path.resolve(__dirname, '../..', 'mcp-client'));

async function main() {
  brain.initDb();
  const db = brain.getDb();

  // Ensure cache table exists
  db.exec(`
    CREATE TABLE IF NOT EXISTS mcp_tools_cache (
      server TEXT NOT NULL,
      tool_name TEXT NOT NULL,
      description TEXT,
      input_schema TEXT,
      scanned_at TEXT DEFAULT (datetime('now')),
      PRIMARY KEY (server, tool_name)
    )
  `);

  const configs = mcpClient.loadMcpConfigs();
  const serverNames = Object.keys(configs);
  console.log('[mcp-scan] Found ' + serverNames.length + ' MCP servers: ' + serverNames.join(', '));

  let totalTools = 0;
  let successServers = 0;
  const failedServers = [];

  for (const [name, config] of Object.entries(configs)) {
    try {
      const conn = await mcpClient.getConnection(name);
      const tools = await conn.listTools();

      // Clear old tools for this server and insert fresh
      db.prepare('DELETE FROM mcp_tools_cache WHERE server = ?').run(name);
      const insert = db.prepare(
        'INSERT INTO mcp_tools_cache (server, tool_name, description, input_schema) VALUES (?, ?, ?, ?)'
      );
      for (const tool of tools) {
        insert.run(name, tool.name, tool.description || '', JSON.stringify(tool.inputSchema || {}));
      }

      totalTools += tools.length;
      successServers++;
      console.log('  ' + name + ': ' + tools.length + ' tools');
    } catch (err) {
      failedServers.push(name + ': ' + err.message.slice(0, 80));
      console.log('  ' + name + ': FAILED - ' + err.message.slice(0, 80));
    }
  }

  // Update scan metadata
  db.exec(`
    CREATE TABLE IF NOT EXISTS mcp_scan_meta (
      key TEXT PRIMARY KEY,
      value TEXT
    )
  `);
  const upsert = db.prepare('INSERT OR REPLACE INTO mcp_scan_meta (key, value) VALUES (?, ?)');
  upsert.run('last_scan', new Date().toISOString());
  upsert.run('server_count', String(serverNames.length));
  upsert.run('tool_count', String(totalTools));

  console.log('\n[mcp-scan] Done: ' + successServers + '/' + serverNames.length + ' servers, ' + totalTools + ' tools');
  if (failedServers.length > 0) {
    console.log('Failed: ' + failedServers.join(', '));
  }

  brain.closeDb();
}

// Export for skill-planner; also run directly when invoked as CLI script
module.exports = { run: main };

if (require.main === module) {
  main().catch(function(err) {
    console.error('[mcp-scan] Error:', err.message);
    process.exit(1);
  });
}
