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

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

// 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, '..');

// 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}`);
}

try {
  // 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);
  }

  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');
} catch (err) {
  // Don't fail install on setup errors
  console.warn('[mcpd] Setup warning:', err.message);
}
