#!/usr/bin/env node

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { AirtableServer } from './server.js';

async function main() {
  const apiKey = process.env.AIRTABLE_API_KEY;

  if (!apiKey) {
    console.error('Error: AIRTABLE_API_KEY environment variable is required');
    console.error('Please set your Airtable API key:');
    console.error('  export AIRTABLE_API_KEY=your_api_key_here');
    process.exit(1);
  }

  const server = new AirtableServer({
    apiKey,
    serverName: '@mcpengine/airtable',
    serverVersion: '1.0.0',
  });

  const transport = new StdioServerTransport();

  // Graceful shutdown
  const cleanup = async () => {
    console.error('Shutting down Airtable MCP server...');
    process.exit(0);
  };

  process.on('SIGINT', cleanup);
  process.on('SIGTERM', cleanup);

  process.on('uncaughtException', (error) => {
    console.error('Uncaught exception:', error);
    process.exit(1);
  });

  process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled rejection at:', promise, 'reason:', reason);
    process.exit(1);
  });

  await server.connect(transport);
  console.error('Airtable MCP server running on stdio');
}

main().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});
