#!/usr/bin/env node
import puppeteer from 'puppeteer';
import { execSync } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import { mcpConfigs } from './mcp-configs.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// ONLY these 3 MCPs
const TARGETS = ['pipedrive', 'helpscout', 'basecamp'];
const configs = mcpConfigs.filter(c => TARGETS.includes(c.id));

console.log('Configs found:', configs.map(c => c.id));

function generateHTML(config) {
  const { name, color, question, statLabel, statValue, statLabel2, statValue2, rows, insight } = config;
  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=1920, height=1080">
  <title>${name} MCP Demo</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #0a0a12;
      --card: #12121c;
      --border: rgba(255,255,255,0.08);
      --text: #ffffff;
      --text-dim: #888;
      --accent: ${color};
      --gradient: linear-gradient(135deg, #667eea, #764ba2);
      --green: #22c55e;
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: 'Inter', -apple-system, sans-serif;
      background: var(--bg);
      width: 1920px;
      height: 1080px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .scene {
      width: 1920px;
      height: 1080px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: radial-gradient(ellipse at 50% 0%, ${color}15 0%, transparent 60%);
    }
    .chat {
      width: 900px;
      background: var(--card);
      border-radius: 20px;
      border: 1px solid var(--border);
      box-shadow: 0 40px 80px rgba(0,0,0,0.5);
      overflow: hidden;
      opacity: 0;
      transform: translateY(30px);
      transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .chat.visible { opacity: 1; transform: translateY(0); }
    .chat-header {
      padding: 16px 20px;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .dots { display: flex; gap: 6px; }
    .dot { width: 12px; height: 12px; border-radius: 50%; }
    .dot.red { background: #ff5f56; }
    .dot.yellow { background: #ffbd2e; }
    .dot.green { background: #27ca40; }
    .chat-title {
      flex: 1;
      text-align: center;
      font-size: 13px;
      color: var(--text-dim);
      font-weight: 500;
    }
    .messages {
      padding: 24px;
      min-height: 500px;
      display: flex;
      flex-direction: column;
      gap: 20px;
    }
    .msg {
      max-width: 85%;
      padding: 14px 18px;
      border-radius: 16px;
      font-size: 15px;
      line-height: 1.5;
      opacity: 0;
      transform: translateY(15px);
      transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .msg.visible { opacity: 1; transform: translateY(0); }
    .msg.user {
      align-self: flex-end;
      background: var(--gradient);
      color: var(--text);
      border-bottom-right-radius: 4px;
    }
    .msg.ai {
      align-self: flex-start;
      background: rgba(255,255,255,0.05);
      color: var(--text);
      border-bottom-left-radius: 4px;
    }
    .typing {
      display: flex;
      gap: 4px;
      padding: 14px 18px;
      background: rgba(255,255,255,0.05);
      border-radius: 16px;
      border-bottom-left-radius: 4px;
      width: fit-content;
      opacity: 0;
      transition: opacity 0.3s;
    }
    .typing.visible { opacity: 1; }
    .typing span {
      width: 6px;
      height: 6px;
      background: var(--text-dim);
      border-radius: 50%;
      animation: bounce 1.2s infinite;
    }
    .typing span:nth-child(2) { animation-delay: 0.15s; }
    .typing span:nth-child(3) { animation-delay: 0.3s; }
    @keyframes bounce {
      0%, 60%, 100% { transform: translateY(0); }
      30% { transform: translateY(-6px); }
    }
    .mcp-card {
      background: #fff;
      border-radius: 12px;
      overflow: hidden;
      margin-top: 12px;
      box-shadow: 0 4px 20px ${color}25;
      opacity: 0;
      transform: scale(0.95);
      transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .mcp-card.visible { opacity: 1; transform: scale(1); }
    .mcp-head {
      padding: 14px 16px;
      border-bottom: 1px solid #e5e7eb;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .mcp-logo {
      background: var(--accent);
      color: #fff;
      font-weight: 700;
      font-size: 11px;
      padding: 4px 8px;
      border-radius: 4px;
    }
    .mcp-head-text { font-size: 13px; color: #1a1a2e; font-weight: 600; }
    .mcp-stats {
      display: flex;
      gap: 24px;
      padding: 14px 16px;
      background: #f8fafc;
    }
    .stat-value { font-size: 20px; font-weight: 700; color: #1a1a2e; }
    .stat-value.green { color: var(--green); }
    .stat-label { font-size: 10px; color: #64748b; text-transform: uppercase; margin-top: 2px; }
    .mcp-rows { padding: 8px 0; }
    .mcp-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 16px;
      font-size: 13px;
      color: #1a1a2e;
      opacity: 0;
      transform: translateX(-10px);
      transition: all 0.3s ease;
    }
    .mcp-row.visible { opacity: 1; transform: translateX(0); }
    .mcp-row-label { font-weight: 500; }
    .mcp-row-value { font-weight: 600; color: #64748b; }
    .insight {
      background: rgba(34, 197, 94, 0.1);
      border: 1px solid rgba(34, 197, 94, 0.3);
      border-radius: 12px;
      padding: 14px 16px;
      margin-top: 12px;
      opacity: 0;
      transform: translateY(10px);
      transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .insight.visible { opacity: 1; transform: translateY(0); }
    .insight-title {
      font-size: 12px;
      font-weight: 600;
      color: var(--green);
      margin-bottom: 6px;
    }
    .insight-text {
      font-size: 14px;
      color: var(--text);
      line-height: 1.5;
    }
    .input-area {
      padding: 16px 20px;
      border-top: 1px solid var(--border);
    }
    .input-box {
      display: flex;
      align-items: center;
      gap: 12px;
      background: rgba(255,255,255,0.03);
      border: 1px solid var(--border);
      border-radius: 12px;
      padding: 12px 14px;
    }
    .input-box.active {
      border-color: var(--accent);
      box-shadow: 0 0 0 3px ${color}25;
    }
    .input-text {
      flex: 1;
      font-size: 14px;
      color: var(--text);
    }
    .input-text .placeholder { color: var(--text-dim); }
    .input-text .cursor {
      display: inline-block;
      width: 2px;
      height: 16px;
      background: var(--accent);
      margin-left: 1px;
      vertical-align: text-bottom;
      animation: blink 0.8s step-end infinite;
    }
    @keyframes blink { 50% { opacity: 0; } }
    .send-btn {
      width: 32px;
      height: 32px;
      border-radius: 8px;
      background: var(--card);
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s;
    }
    .send-btn.ready { background: var(--gradient); }
    .send-btn svg { width: 16px; height: 16px; fill: #fff; }
  </style>
</head>
<body>
  <div class="scene">
    <div class="chat" id="chat">
      <div class="chat-header">
        <div class="dots">
          <span class="dot red"></span>
          <span class="dot yellow"></span>
          <span class="dot green"></span>
        </div>
        <div class="chat-title">AI Assistant · ${name} Connected</div>
        <div style="width:50px"></div>
      </div>
      <div class="messages">
        <div class="msg user" id="userMsg">${question}</div>
        <div class="typing" id="typing">
          <span></span><span></span><span></span>
        </div>
        <div class="msg ai" id="aiMsg">
          Here's what I found:
          <div class="mcp-card" id="mcpCard">
            <div class="mcp-head">
              <span class="mcp-logo">${name.substring(0, 2).toLowerCase()}</span>
              <span class="mcp-head-text">${name}</span>
            </div>
            <div class="mcp-stats">
              <div>
                <div class="stat-value green">${statValue}</div>
                <div class="stat-label">${statLabel}</div>
              </div>
              <div>
                <div class="stat-value">${statValue2}</div>
                <div class="stat-label">${statLabel2}</div>
              </div>
            </div>
            <div class="mcp-rows">
              <div class="mcp-row" id="row1">
                <span class="mcp-row-label">${rows[0].label}</span>
                <span class="mcp-row-value">${rows[0].value}</span>
              </div>
              <div class="mcp-row" id="row2">
                <span class="mcp-row-label">${rows[1].label}</span>
                <span class="mcp-row-value">${rows[1].value}</span>
              </div>
              <div class="mcp-row" id="row3">
                <span class="mcp-row-label">${rows[2].label}</span>
                <span class="mcp-row-value">${rows[2].value}</span>
              </div>
            </div>
          </div>
          <div class="insight" id="insight">
            <div class="insight-title">💡 Recommendation</div>
            <div class="insight-text">${insight}</div>
          </div>
        </div>
      </div>
      <div class="input-area">
        <div class="input-box" id="inputBox">
          <div class="input-text" id="inputText"><span class="placeholder">Ask anything...</span></div>
          <button class="send-btn" id="sendBtn">
            <svg viewBox="0 0 24 24"><path d="M2 21L23 12 2 3v7l15 2-15 2z"/></svg>
          </button>
        </div>
      </div>
    </div>
  </div>
  <script>
    const question = ${JSON.stringify(question)};
    function ease(t) { return t < 0.5 ? 4*t*t*t : 1 - Math.pow(-2*t + 2, 3) / 2; }
    function phase(scroll, start, end) {
      if (scroll < start) return 0;
      if (scroll > end) return 1;
      return (scroll - start) / (end - start);
    }
    function updateScene(scroll) {
      const chat = document.getElementById('chat');
      const inputBox = document.getElementById('inputBox');
      const inputText = document.getElementById('inputText');
      const sendBtn = document.getElementById('sendBtn');
      const userMsg = document.getElementById('userMsg');
      const typing = document.getElementById('typing');
      const aiMsg = document.getElementById('aiMsg');
      const mcpCard = document.getElementById('mcpCard');
      const row1 = document.getElementById('row1');
      const row2 = document.getElementById('row2');
      const row3 = document.getElementById('row3');
      const insight = document.getElementById('insight');
      
      chat.classList.toggle('visible', scroll >= 0.02);
      
      const typeProgress = phase(scroll, 0.08, 0.28);
      const chars = Math.floor(ease(typeProgress) * question.length);
      
      if (scroll < 0.08) {
        inputText.innerHTML = '<span class="placeholder">Ask anything...</span>';
        inputBox.classList.remove('active');
        sendBtn.classList.remove('ready');
      } else if (scroll < 0.30) {
        inputBox.classList.add('active');
        inputText.innerHTML = (chars > 0 ? question.substring(0, chars) : '') + '<span class="cursor"></span>';
        sendBtn.classList.toggle('ready', chars === question.length);
      } else {
        inputBox.classList.remove('active');
        inputText.innerHTML = '<span class="placeholder">Ask anything...</span>';
        sendBtn.classList.remove('ready');
      }
      
      userMsg.classList.toggle('visible', scroll >= 0.30);
      typing.classList.toggle('visible', scroll >= 0.38 && scroll < 0.48);
      aiMsg.classList.toggle('visible', scroll >= 0.48);
      mcpCard.classList.toggle('visible', scroll >= 0.55);
      row1.classList.toggle('visible', scroll >= 0.62);
      row2.classList.toggle('visible', scroll >= 0.67);
      row3.classList.toggle('visible', scroll >= 0.72);
      insight.classList.toggle('visible', scroll >= 0.80);
    }
    window.updateScene = updateScene;
    updateScene(0);
  </script>
</body>
</html>`;
}

async function renderVideo(config, browser) {
  const htmlPath = path.join(__dirname, 'output', config.id + '.html');
  const framesDir = path.join(__dirname, 'output', config.id + '-frames');
  const mp4Path = path.join(__dirname, 'output', config.id + '.mp4');
  
  fs.writeFileSync(htmlPath, generateHTML(config));
  fs.rmSync(framesDir, { recursive: true, force: true });
  fs.mkdirSync(framesDir, { recursive: true });
  
  const page = await browser.newPage();
  await page.setViewport({ width: 1920, height: 1080 });
  await page.goto('file://' + htmlPath, { waitUntil: 'networkidle0' });
  await new Promise(r => setTimeout(r, 300));
  
  const fps = 30;
  const totalFrames = 300;
  
  for (let i = 0; i < totalFrames; i++) {
    const scroll = i / (totalFrames - 1);
    await page.evaluate(s => window.updateScene(s), scroll);
    await new Promise(r => setTimeout(r, 15));
    await page.screenshot({ 
      path: path.join(framesDir, 'frame-' + String(i+1).padStart(4,'0') + '.png'),
      type: 'png'
    });
  }
  
  await page.close();
  
  execSync('ffmpeg -y -framerate ' + fps + ' -i "' + framesDir + '/frame-%04d.png" -c:v libx264 -pix_fmt yuv420p -crf 20 "' + mp4Path + '"', { stdio: 'pipe' });
  fs.rmSync(framesDir, { recursive: true, force: true });
  
  return mp4Path;
}

async function main() {
  console.log('\n🎬 Generating ' + configs.length + ' MCP videos: ' + configs.map(c => c.name).join(', ') + '\n');
  
  const browser = await puppeteer.launch({ 
    headless: true,
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    args: ['--no-sandbox']
  });
  
  const results = [];
  
  for (let i = 0; i < configs.length; i++) {
    const config = configs[i];
    const start = Date.now();
    process.stdout.write('[' + (i+1) + '/' + configs.length + '] ' + config.name + '... ');
    
    try {
      await renderVideo(config, browser);
      console.log('✓ (' + Math.round((Date.now() - start) / 1000) + 's)');
      results.push({ name: config.name, id: config.id, success: true });
    } catch (err) {
      console.log('✗ ' + err.message);
      results.push({ name: config.name, id: config.id, success: false, error: err.message });
    }
  }
  
  await browser.close();
  console.log('\n✓ Done! Videos saved to output/\n');
  console.log('Results:');
  results.forEach(r => console.log('  ' + (r.success ? '✓' : '✗') + ' ' + r.name + (r.error ? ': ' + r.error : '')));
}

main().catch(console.error);
