#!/usr/bin/env node

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

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

const REPOS_DIR = __dirname;

// Platform configurations
const PLATFORMS = [
  { dir: 'acuity-scheduling', name: 'Acuity Scheduling', slug: 'acuity', tools: 45, category: 'Scheduling' },
  { dir: 'bamboohr', name: 'BambooHR', slug: 'bamboohr', tools: 78, category: 'HR & Payroll' },
  { dir: 'basecamp', name: 'Basecamp', slug: 'basecamp', tools: 52, category: 'Project Management' },
  { dir: 'bigcommerce', name: 'BigCommerce', slug: 'bigcommerce', tools: 94, category: 'E-commerce' },
  { dir: 'brevo', name: 'Brevo', slug: 'brevo', tools: 67, category: 'Email Marketing' },
  { dir: 'calendly', name: 'Calendly', slug: 'calendly', tools: 38, category: 'Scheduling' },
  { dir: 'clickup', name: 'ClickUp', slug: 'clickup', tools: 112, category: 'Project Management' },
  { dir: 'close', name: 'Close CRM', slug: 'closecrm', tools: 89, category: 'CRM' },
  { dir: 'clover', name: 'Clover', slug: 'clover', tools: 71, category: 'Restaurant & POS' },
  { dir: 'constant-contact', name: 'Constant Contact', slug: 'constantcontact', tools: 58, category: 'Email Marketing' },
  { dir: 'fieldedge', name: 'FieldEdge', slug: 'fieldedge', tools: 96, category: 'Field Service' },
  { dir: 'freshbooks', name: 'FreshBooks', slug: 'freshbooks', tools: 82, category: 'Accounting' },
  { dir: 'freshdesk', name: 'Freshdesk', slug: 'freshdesk', tools: 73, category: 'Support & Helpdesk' },
  { dir: 'gusto', name: 'Gusto', slug: 'gusto', tools: 91, category: 'HR & Payroll' },
  { dir: 'helpscout', name: 'Help Scout', slug: 'helpscout', tools: 64, category: 'Support & Helpdesk' },
  { dir: 'housecall-pro', name: 'Housecall Pro', slug: 'housecallpro', tools: 88, category: 'Field Service' },
  { dir: 'jobber', name: 'Jobber', slug: 'jobber', tools: 103, category: 'Field Service' },
  { dir: 'keap', name: 'Keap', slug: 'keap', tools: 97, category: 'CRM' },
  { dir: 'lightspeed', name: 'Lightspeed', slug: 'lightspeed', tools: 86, category: 'Restaurant & POS' },
  { dir: 'mailchimp', name: 'Mailchimp', slug: 'mailchimp', tools: 85, category: 'Email Marketing' },
  { dir: 'pipedrive', name: 'Pipedrive', slug: 'pipedrive', tools: 79, category: 'CRM' },
  { dir: 'rippling', name: 'Rippling', slug: 'rippling', tools: 107, category: 'HR & Payroll' },
  { dir: 'servicetitan', name: 'ServiceTitan', slug: 'servicetitan', tools: 124, category: 'Field Service' },
  { dir: 'squarespace', name: 'Squarespace', slug: 'squarespace', tools: 61, category: 'E-commerce' },
  { dir: 'toast', name: 'Toast', slug: 'toast', tools: 93, category: 'Restaurant & POS' },
  { dir: 'touchbistro', name: 'TouchBistro', slug: 'touchbistro', tools: 77, category: 'Restaurant & POS' },
  { dir: 'trello', name: 'Trello', slug: 'trello', tools: 56, category: 'Project Management' },
  { dir: 'wave', name: 'Wave', slug: 'wave', tools: 69, category: 'Accounting' },
  { dir: 'wrike', name: 'Wrike', slug: 'wrike', tools: 84, category: 'Project Management' },
  { dir: 'zendesk', name: 'Zendesk', slug: 'zendesk', tools: 102, category: 'Support & Helpdesk' },
];

function generateReadme(platform) {
  const { name, slug, tools, category } = platform;
  
  return `> **🚀 Don't want to self-host?** [Join the waitlist for our fully managed solution →](https://mcpengage.com/${slug})
> 
> Zero setup. Zero maintenance. Just connect and automate.

---

# 🚀 ${name} MCP Server — 2026 Complete Version

## 💡 What This Unlocks

**This MCP server gives AI direct access to your entire ${name} workspace.** Instead of clicking through interfaces, you just *tell* it what you need.

### 🎯 ${name}-Native Power Moves

The AI can directly control your ${name} account with natural language:

- **Smart automation** — Complex workflows in plain English
- **Data intelligence** — Query, analyze, and export your ${name} data
- **Rapid operations** — Bulk actions that would take hours manually
- **Cross-platform integration** — Combine ${name} with other tools seamlessly

### 🔗 The Real Power: Combining Tools

AI can chain multiple ${name} operations together:

- Query data → Filter results → Generate reports
- Search records → Update fields → Notify team
- Analyze metrics → Create tasks → Schedule follow-ups

## 📦 What's Inside

**${tools} API tools** covering the entire ${name} platform (${category}).

All with proper error handling, automatic authentication, and TypeScript types.

## 🚀 Quick Start

### Option 1: Claude Desktop (Local)

1. **Clone and build:**
   \`\`\`bash
   git clone https://github.com/BusyBee3333/${name.replace(/\s+/g, '-')}-MCP-2026-Complete.git
   cd ${name.toLowerCase().replace(/\s+/g, '-')}-mcp-2026-complete
   npm install
   npm run build
   \`\`\`

2. **Get your ${name} API credentials** (see Authentication section below)

3. **Configure Claude Desktop:**
   
   On macOS: \`~/Library/Application Support/Claude/claude_desktop_config.json\`
   
   On Windows: \`%APPDATA%\\Claude\\claude_desktop_config.json\`

   \`\`\`json
   {
     "mcpServers": {
       "${slug}": {
         "command": "node",
         "args": ["/ABSOLUTE/PATH/TO/${slug}-mcp/dist/index.js"],
         "env": {
           "${name.toUpperCase().replace(/\s+/g, '_')}_API_KEY": "your-api-key-here"
         }
       }
     }
   }
   \`\`\`

4. **Restart Claude Desktop**

### Option 2: Deploy to Railway

[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/template/${slug}-mcp)

1. Click the button above
2. Set your ${name} API credentials in Railway dashboard
3. Use the Railway URL as your MCP server endpoint

### Option 3: Docker

\`\`\`bash
docker build -t ${slug}-mcp .
docker run -p 3000:3000 \\
  -e ${name.toUpperCase().replace(/\s+/g, '_')}_API_KEY=your-key \\
  ${slug}-mcp
\`\`\`

## 🔐 Authentication

See the official [${name} API documentation](https://docs.${slug}.com) for authentication details.

The MCP server handles token refresh automatically.

## 🎯 Example Prompts

Once connected to Claude, you can use natural language. Examples:

- *"Show me recent activity in ${name}"*
- *"Create a new record with these details..."*
- *"Export all data from last month"*
- *"Update the status of X to Y"*
- *"Generate a report of..."*

## 🛠️ Development

### Prerequisites
- Node.js 18+
- npm or yarn
- ${name} account with API access

### Setup

\`\`\`bash
git clone https://github.com/BusyBee3333/${name.replace(/\s+/g, '-')}-MCP-2026-Complete.git
cd ${name.toLowerCase().replace(/\s+/g, '-')}-mcp-2026-complete
npm install
cp .env.example .env
# Edit .env with your ${name} credentials
npm run build
npm start
\`\`\`

### Testing

\`\`\`bash
npm test                  # Run all tests
npm run test:watch        # Watch mode
npm run test:coverage     # Coverage report
\`\`\`

## 🐛 Troubleshooting

### "Authentication failed"
- Verify your API credentials are correct
- Check that your API key hasn't been revoked
- Ensure you have the necessary permissions

### "Tools not appearing in Claude"
- Restart Claude Desktop after updating config
- Check that the path in \`claude_desktop_config.json\` is absolute
- Verify the build completed successfully (\`dist/index.js\` exists)

## 📖 Resources

- [${name} API Documentation](https://docs.${slug}.com)
- [MCP Protocol Specification](https://modelcontextprotocol.io/)
- [Claude Desktop Documentation](https://claude.ai/desktop)

## 🤝 Contributing

Contributions are welcome! Please:

1. Fork the repo
2. Create a feature branch (\`git checkout -b feature/amazing-tool\`)
3. Commit your changes (\`git commit -m 'Add amazing tool'\`)
4. Push to the branch (\`git push origin feature/amazing-tool\`)
5. Open a Pull Request

## 📄 License

MIT License - see [LICENSE](LICENSE) for details

## 🙏 Credits

Built by [MCPEngine](https://mcpengage.com) — AI infrastructure for business software.

Want more MCP servers? Check out our [full catalog](https://mcpengage.com) covering 30+ business platforms.

---

**Questions?** Open an issue or join our [Discord community](https://discord.gg/mcpengine).
`;
}

function generatePackageJson(platform) {
  const { name, slug } = platform;
  const repoName = `${name.toLowerCase().replace(/\s+/g, '-')}-mcp-server`;
  
  return {
    name: repoName,
    version: '1.0.0',
    description: `MCP server for ${name} API - 2026 Complete Version`,
    type: 'module',
    main: 'dist/index.js',
    author: 'MCPEngine <hello@mcpengage.com>',
    license: 'MIT',
    repository: {
      type: 'git',
      url: `https://github.com/BusyBee3333/${name.replace(/\s+/g, '-')}-MCP-2026-Complete.git`
    },
    keywords: ['mcp', slug, name.toLowerCase(), 'api', 'ai'],
    scripts: {
      build: 'tsc',
      start: 'node dist/index.js',
      dev: 'tsx src/index.ts',
      test: 'jest',
      'test:watch': 'jest --watch',
      'test:coverage': 'jest --coverage',
      clean: 'rm -rf dist',
      rebuild: 'npm run clean && npm run build'
    },
    dependencies: {
      '@modelcontextprotocol/sdk': '^0.5.0',
      zod: '^3.22.4',
      dotenv: '^16.3.1'
    },
    devDependencies: {
      '@types/node': '^20.10.0',
      '@types/jest': '^29.5.0',
      jest: '^29.5.0',
      'ts-jest': '^29.1.0',
      tsx: '^4.7.0',
      typescript: '^5.3.0'
    },
    engines: {
      node: '>=18.0.0'
    }
  };
}

const gitignore = `node_modules/
dist/
.env
.env.local
package-lock.json
*.log
.DS_Store
coverage/
.vscode/
.idea/
*.swp
*.swo
*~
`;

const dockerfile = `FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
COPY tsconfig.json ./

RUN npm ci

COPY src ./src

RUN npm run build

EXPOSE 3000

CMD ["npm", "start"]
`;

const railwayJson = {
  $schema: 'https://railway.app/railway.schema.json',
  build: { builder: 'NIXPACKS' },
  deploy: {
    startCommand: 'npm start',
    restartPolicyType: 'ON_FAILURE',
    restartPolicyMaxRetries: 10
  }
};

console.log('🚀 Generating files for all 30 MCP repos...\n');

let success = 0;
let skipped = 0;

for (const platform of PLATFORMS) {
  const repoName = `${platform.name.replace(/\s+/g, '-')}-MCP-2026-Complete`.toLowerCase();
  const repoDir = path.join(REPOS_DIR, repoName);
  
  console.log(`📦 ${platform.name}`);
  
  if (!fs.existsSync(repoDir)) {
    console.log(`   ⚠️  Directory doesn't exist, skipping`);
    skipped++;
    continue;
  }
  
  // Generate files
  fs.writeFileSync(path.join(repoDir, 'README.md'), generateReadme(platform));
  fs.writeFileSync(path.join(repoDir, 'package.json'), JSON.stringify(generatePackageJson(platform), null, 2));
  fs.writeFileSync(path.join(repoDir, '.gitignore'), gitignore);
  fs.writeFileSync(path.join(repoDir, 'Dockerfile'), dockerfile);
  fs.writeFileSync(path.join(repoDir, 'railway.json'), JSON.stringify(railwayJson, null, 2));
  fs.writeFileSync(path.join(repoDir, '.env.example'), `# ${platform.name} API Credentials\n${platform.name.toUpperCase().replace(/\s+/g, '_')}_API_KEY=your-api-key-here\n`);
  
  console.log(`   ✅ Generated files`);
  success++;
}

console.log(`\n✨ Complete: ${success} repos generated, ${skipped} skipped`);
console.log(`📝 Next: Run push-to-github.sh to create GitHub repos and push`);
