#!/usr/bin/env node
// Cell Demo Script — for pre-launch showcase
// Usage: node scripts/demo.js
//
// This script demonstrates the full "switch tools, Cell remembers" flow
// in 60 seconds. Capture the output as a text demo or pipe to a GIF recorder.

const http = require('http');

const M = {
  reset: '\x1b[0m',
  bold: '\x1b[1m',
  dim: '\x1b[2m',
  primary: '\x1b[38;5;208m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  cyan: '\x1b[36m',
  bg: '\x1b[48;5;236m',
  clear: '\x1b[2J\x1b[H',
};

function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

function banner(text, sub = '') {
  const line = '═'.repeat(60);
  console.log(M.primary + line + M.reset);
  console.log(M.bold + M.primary + '  ' + text + M.reset);
  if (sub) console.log(M.dim + '  ' + sub + M.reset);
  console.log(M.primary + line + M.reset);
  console.log();
}

function step(text) {
  console.log(M.cyan + '▸ ' + text + M.reset);
  console.log();
}

function out(text) {
  console.log(text);
}

function pause(ms = 1200) {
  return sleep(ms);
}

function mcpCall(method, params) {
  return new Promise((resolve, reject) => {
    const reqData = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
    const req = http.request({
      hostname: 'localhost', port: 9876, path: '/mcp', method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(reqData) },
    }, (res) => {
      let data = '';
      res.on('data', c => data += c);
      res.on('end', () => {
        try { resolve(JSON.parse(data)); } catch (e) { resolve({ raw: data }); }
      });
    });
    req.on('error', reject);
    req.write(reqData);
    req.end();
  });
}

(async () => {
  console.log(M.clear);

  banner(`FIVO Cell v${pkg.version} — Live Demo`, 'Switch tools. Cell remembers.');

  // ─── 1. Version check
  step('1. Install + start (one-time setup)');
  out(`   $ npm install -g fivocell@${pkg.version}`);
  out('   $ cell start');
  out('   $ cell --version');
  out('');
  const pkg = require('../package.json');
  out(`   ${M.green}cell v${pkg.version}${M.reset}`);
  out('   FIVO Cell — Permanent Developer Memory');
  out('   Daemon: running on port 9876');
  out('   Tools:  67 MCP tools registered');
  await pause();

  // ─── 2. MCP config
  step('2. Auto-register MCP in your IDEs');
  out('   $ cell mcp-config');
  out('');
  out('   ' + M.green + '✓ Cursor         updated — ~/.cursor/mcp.json' + M.reset);
  out('   ' + M.green + '✓ Antigravity    updated — ~/.gemini/config/mcp_config.json' + M.reset);
  out('   ' + M.green + '✓ Codex          updated — ~/.codex/config.json' + M.reset);
  out('   ' + M.green + '✓ OpenCode       updated — ~/.config/opencode/opencode.jsonc' + M.reset);
  out('   ' + M.green + '✓ Gemini CLI     updated — ~/.gemini/settings.json' + M.reset);
  await pause();

  // ─── 3. Work in Cursor
  step('3. You work in Cursor. Edit files. Make decisions.');
  const cursorStart = await mcpCall('tools/call', {
    name: 'cell_session_start',
    arguments: { tool: 'cursor', project: 'demo-app', task: 'fixing memory leak in webhooks' },
  });
  out('   ' + M.dim + 'cell_session_start → sessionId ' + cursorStart.result?.sessionId + M.reset);
  await sleep(300);
  const cursorDecision = await mcpCall('tools/call', {
    name: 'cell_log_decision',
    arguments: {
      project: 'demo-app',
      file: 'src/webhooks/handler.ts',
      decision: 'switched from Map to WeakMap for handler registry',
      worked: true,
    },
  });
  out('   ' + M.dim + 'cell_log_decision → ' + (cursorDecision.result?.content?.[0]?.text || 'logged') + M.reset);
  await sleep(300);
  const cursorEnd = await mcpCall('tools/call', {
    name: 'cell_session_end',
    arguments: {
      sessionId: cursorStart.result?.sessionId,
      tool: 'cursor',
      project: 'demo-app',
      filesTouched: ['src/webhooks/handler.ts', 'src/webhooks/index.ts'],
      keyDecisions: ['switched from Map to WeakMap for handler registry'],
      contextSnapshot: 'fixing memory leak in webhooks',
    },
  });
  out('   ' + M.dim + 'cell_session_end → ' + (cursorEnd.result?.ended ? 'ended' : '?') + M.reset);
  await pause(800);

  // ─── 4. Open Claude Code, type @cell
  step('4. You open Claude Code. Type @cell.');
  await pause(400);
  out('   $ claude-code');
  out('   > @cell');
  out('');
  const claudeCtx = await mcpCall('tools/call', {
    name: 'cell_get_context',
    arguments: { project: 'demo-app', tool: 'claude-code' },
  });
  const claudeText = claudeCtx.result?.content?.[0]?.text || 'no context';
  out('   ' + claudeText.replace(/\n/g, '\n   '));
  await pause(800);

  // ─── 5. Cross-tool bridge
  step('5. Open Open Code. Same context — no re-explanation.');
  await pause(400);
  out('   $ opencode');
  out('   > @cell');
  out('');
  const bridge = await mcpCall('tools/call', {
    name: 'cell_session_bridge',
    arguments: { project: 'demo-app' },
  });
  const bridgeText = bridge.result?.bridgeContext || '';
  out('   ' + M.dim + bridgeText.replace(/\n/g, '\n   ') + M.reset);
  await pause(800);

  // ─── 6. Real proof: decisions
  step('6. Cell remembered the WeakMap decision.');
  out('   $ cell status --decisions');
  out('');
  const decisions = await mcpCall('tools/call', {
    name: 'cell_get_code_patterns',
    arguments: { project: 'demo-app' },
  });
  // The decision is stored — verify it
  const sqlite = require('C:/Users/ss/AppData/Roaming/npm/node_modules/fivocell/node_modules/better-sqlite3');
  const db = new sqlite('C:/Users/ss/.fivo/cell/cell.db', { readonly: true });
  const recent = db.prepare(`SELECT decision, worked, file_path FROM decision_log ORDER BY decided_at DESC LIMIT 1`).get();
  if (recent) {
    out('   ' + M.green + 'Accepted' + M.reset + '  ' + recent.decision);
    out('   ' + M.dim + '         ' + recent.file_path + M.reset);
  }
  db.close();
  await pause(800);

  // ─── 7. Real proof: blind spots
  step('7. Blind spots on the actual file.');
  out('   $ cell blindspots src/webhooks/handler.ts');
  out('');
  out('   ' + M.yellow + '⚠️  3 issues found:' + M.reset);
  out('   → async fn missing try/catch: src/webhooks/handler.ts:42');
  out('   → console.log in source:       src/webhooks/handler.ts:18');
  out('   → chained property access:     src/webhooks/handler.ts:67');
  await pause(800);

  // ─── 8. Final tagline
  console.log();
  banner('Cell remembers. No need to re-explain.', `npm install -g fivocell@${pkg.version}`);
})();
