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

const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');

// Skip in CI or if SKIP_POSTINSTALL is set
if (process.env.CI || process.env.SKIP_POSTINSTALL || process.env.npm_config_ignore_scripts) {
  process.exit(0);
}

const home = process.env.USERPROFILE || process.env.HOME || '';
if (!home) {
  console.warn('[mcpd] Could not determine home directory, skipping setup');
  process.exit(0);
}

const srcDir = path.resolve(__dirname, '..');

// Check if mcpd daemon is running
function isDaemonRunning() {
  try {
    if (os.platform() === 'win32') {
      const result = execSync('tasklist /FI "IMAGENAME eq mcpd.exe" /NH', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
      return result.includes('mcpd.exe');
    } else {
      const result = execSync('pgrep -f "mcpd daemon"', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
      return result.trim().length > 0;
    }
  } catch (e) {
    return false;
  }
}

// Check if daemon is running
const daemonRunning = isDaemonRunning();

// File mappings: source (relative to npm pkg) -> target (relative to home)
const files = [
  { src: 'examples/mcpd.yml', dst: '.mcpd/mcpd.yml' },
  { src: 'examples/mcpserver.json', dst: '.mcpd/mcpserver.json' },
  { src: 'skills/mcpd/SKILL.md', dst: '.agents/skills/mcpd/SKILL.md' },
];

// Directories to create
const dirs = [
  '.mcpd',
  '.mcpd/logs',
  '.mcpd/cache',
  '.agents/skills/mcpd',
];

function copyFile(srcRel, dstRel) {
  const src = path.join(srcDir, srcRel);
  const dst = path.join(home, dstRel);

  // Skip if source doesn't exist
  if (!fs.existsSync(src)) {
    return;
  }

  // Skip if target already exists (don't overwrite user config)
  if (fs.existsSync(dst)) {
    console.log(`[mcpd] Skipped (exists): ${dstRel}`);
    return;
  }

  // Ensure parent directory exists
  const dir = path.dirname(dst);
  fs.mkdirSync(dir, { recursive: true });

  fs.copyFileSync(src, dst);
  console.log(`[mcpd] Created: ${dstRel}`);
}

function createDesktopShortcut() {
  const platform = os.platform();
  const desktopDir = path.join(home, 'Desktop');

  // Check if Desktop exists
  if (!fs.existsSync(desktopDir)) {
    console.log('[mcpd] Desktop folder not found, skipping shortcut');
    return;
  }

  if (platform === 'win32') {
    // Windows: Create .url shortcut file
    const shortcutPath = path.join(desktopDir, 'mcpd Manager.url');
    if (fs.existsSync(shortcutPath)) {
      console.log('[mcpd] Skipped (exists): Desktop shortcut');
      return;
    }

    const content = `[InternetShortcut]
URL=http://localhost:18423/
IconFile=shell32.dll
IconIndex=13
`;

    try {
      fs.writeFileSync(shortcutPath, content, 'utf8');
      console.log('[mcpd] Created: Desktop shortcut (mcpd Manager.url)');
    } catch (err) {
      console.warn('[mcpd] Could not create desktop shortcut:', err.message);
    }
  } else if (platform === 'darwin') {
    // macOS: Create .webloc file
    const shortcutPath = path.join(desktopDir, 'mcpd Manager.webloc');
    if (fs.existsSync(shortcutPath)) {
      console.log('[mcpd] Skipped (exists): Desktop shortcut');
      return;
    }

    const content = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>URL</key>
  <string>http://localhost:18423/</string>
</dict>
</plist>
`;

    try {
      fs.writeFileSync(shortcutPath, content, 'utf8');
      console.log('[mcpd] Created: Desktop shortcut (mcpd Manager.webloc)');
    } catch (err) {
      console.warn('[mcpd] Could not create desktop shortcut:', err.message);
    }
  } else {
    // Linux: Create .desktop file
    const shortcutPath = path.join(desktopDir, 'mcpd-manager.desktop');
    if (fs.existsSync(shortcutPath)) {
      console.log('[mcpd] Skipped (exists): Desktop shortcut');
      return;
    }

    const content = `[Desktop Entry]
Version=1.0
Type=Link
Name=mcpd Manager
Comment=MCP Server Manager
URL=http://localhost:18423/
Icon=utilities-terminal
Terminal=false
`;

    try {
      fs.writeFileSync(shortcutPath, content, 'utf8');
      fs.chmodSync(shortcutPath, '755');
      console.log('[mcpd] Created: Desktop shortcut (mcpd-manager.desktop)');
    } catch (err) {
      console.warn('[mcpd] Could not create desktop shortcut:', err.message);
    }
  }
}

try {
  // Check if binary file is locked (Windows only issue)
  if (os.platform() === 'win32' && daemonRunning) {
    const binaryPath = path.join(srcDir, 'bin', 'win-x64', 'mcpd.exe');
    try {
      // Try to open the file exclusively to check if it's locked
      const fd = fs.openSync(binaryPath, 'r+');
      fs.closeSync(fd);
    } catch (err) {
      if (err.code === 'EBUSY' || err.code === 'EPERM') {
        console.warn('[mcpd] Warning: mcpd.exe is currently in use');
        console.warn('[mcpd] The upgrade completed, but binary may not be updated');
        console.warn('[mcpd] Please stop the daemon and reinstall if needed:');
        console.warn('[mcpd]   mcpd down && npm install -g @juncai/mcpd');
      }
    }
  }

  // Create directories
  for (const dir of dirs) {
    const target = path.join(home, dir);
    fs.mkdirSync(target, { recursive: true });
  }

  // Copy files (skip if exists)
  for (const file of files) {
    copyFile(file.src, file.dst);
  }

  // Create desktop shortcut
  createDesktopShortcut();

  console.log('[mcpd] Setup complete!');
  console.log('[mcpd] Config: ~/.mcpd/mcpd.yml');
  console.log('[mcpd] Servers: ~/.mcpd/mcpserver.json');
  console.log('[mcpd] Skill: ~/.agents/skills/mcpd/SKILL.md');
  console.log('[mcpd] ');
  console.log('[mcpd] Quick start:');
  console.log('[mcpd]   1. Run: mcpd up');
  console.log('[mcpd]   2. Browser opens automatically');
  console.log('[mcpd]   3. Or open: http://localhost:18423/');

  // Warn if daemon was running during upgrade
  if (daemonRunning) {
    console.log('[mcpd] ');
    console.log('[mcpd] ============================================');
    console.log('[mcpd]  mcpd daemon was detected running!');
    console.log('[mcpd]  Please restart daemon to use new version:');
    console.log('[mcpd] ');
    console.log('[mcpd]    mcpd down && mcpd up');
    console.log('[mcpd] ============================================');
  }
} catch (err) {
  // Don't fail install on setup errors
  console.warn('[mcpd] Setup warning:', err.message);
}
