#!/usr/bin/env node

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

async function main() {
  // Check for required environment variable
  const apiKey = process.env.NOTION_API_KEY;
  if (!apiKey) {
    console.error('Error: NOTION_API_KEY environment variable is required');
    process.exit(1);
  }

  // Create server instance
  const server = new NotionServer({ apiKey });

  // Create stdio transport
  const transport = new StdioServerTransport();

  // Connect server to transport
  await server.connect(transport);

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

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

  // Handle uncaught errors
  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);
  });

  console.error('Notion MCP server running on stdio');
}

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