#!/usr/bin/env node
import { ShopifyClient } from './clients/shopify.js';
import { ShopifyMCPServer } from './server.js';

interface EnvironmentConfig {
  accessToken: string;
  store: string;
  apiVersion?: string;
  httpMode: boolean;
  port?: number;
}

/**
 * Validate and load environment configuration
 */
function loadConfig(): EnvironmentConfig {
  const accessToken = process.env.SHOPIFY_ACCESS_TOKEN;
  const store = process.env.SHOPIFY_STORE;
  const apiVersion = process.env.SHOPIFY_API_VERSION;
  const httpMode = process.argv.includes('--http');
  const portArg = process.argv.find(arg => arg.startsWith('--port='));
  const port = portArg ? parseInt(portArg.split('=')[1] || '3000', 10) : 3000;

  // Validate required environment variables
  if (!accessToken) {
    console.error('Error: SHOPIFY_ACCESS_TOKEN environment variable is required');
    console.error('Get your access token from: Settings > Apps and sales channels > Develop apps');
    process.exit(1);
  }

  if (!store) {
    console.error('Error: SHOPIFY_STORE environment variable is required');
    console.error('Example: your-store-name (without .myshopify.com)');
    process.exit(1);
  }

  // Validate store format (should not include .myshopify.com)
  if (store.includes('.myshopify.com')) {
    console.error('Error: SHOPIFY_STORE should not include .myshopify.com');
    console.error('Example: Use "your-store-name" instead of "your-store-name.myshopify.com"');
    process.exit(1);
  }

  return {
    accessToken,
    store,
    apiVersion,
    httpMode,
    port,
  };
}

/**
 * Setup graceful shutdown handlers
 */
function setupGracefulShutdown(cleanup: () => Promise<void>): void {
  const handleShutdown = async (signal: string) => {
    console.log(`\n[${signal}] Shutting down gracefully...`);
    try {
      await cleanup();
      console.log('Shutdown complete');
      process.exit(0);
    } catch (error) {
      console.error('Error during shutdown:', error);
      process.exit(1);
    }
  };

  process.on('SIGINT', () => handleShutdown('SIGINT'));
  process.on('SIGTERM', () => handleShutdown('SIGTERM'));
}

/**
 * Start HTTP/SSE server (for --http mode)
 */
async function startHttpServer(
  server: ShopifyMCPServer,
  port: number
): Promise<() => Promise<void>> {
  // Note: HTTP/SSE transport requires additional setup
  // For now, this is a placeholder for future implementation
  console.log(`HTTP mode requested on port ${port}`);
  console.log('Note: HTTP/SSE transport not yet implemented');
  console.log('Falling back to stdio mode...');
  
  await server.start();
  
  return async () => {
    console.log('HTTP server cleanup');
  };
}

/**
 * Start stdio server (default mode)
 */
async function startStdioServer(
  server: ShopifyMCPServer
): Promise<() => Promise<void>> {
  await server.start();
  
  return async () => {
    console.log('Stdio server cleanup');
  };
}

/**
 * Health check endpoint (when in HTTP mode)
 */
function createHealthCheckHandler() {
  return async (req: unknown, res: unknown) => {
    // Placeholder for HTTP health check
    console.log('Health check called');
  };
}

/**
 * Main entry point
 */
async function main() {
  console.log('='.repeat(50));
  console.log('Shopify MCP Server v1.0.0');
  console.log('='.repeat(50));

  // Load configuration
  const config = loadConfig();

  console.log(`Store: ${config.store}`);
  console.log(`API Version: ${config.apiVersion || '2024-01'}`);
  console.log(`Mode: ${config.httpMode ? `HTTP (port ${config.port})` : 'stdio'}`);
  console.log('='.repeat(50));

  // Initialize Shopify client
  const shopifyClient = new ShopifyClient({
    accessToken: config.accessToken,
    store: config.store,
    apiVersion: config.apiVersion,
  });

  // Initialize MCP server
  const mcpServer = new ShopifyMCPServer({
    name: '@mcpengine/shopify',
    version: '1.0.0',
    shopifyClient,
  });

  // Start server in appropriate mode
  let cleanup: () => Promise<void>;

  if (config.httpMode) {
    cleanup = await startHttpServer(mcpServer, config.port || 3000);
  } else {
    cleanup = await startStdioServer(mcpServer);
  }

  // Setup graceful shutdown
  setupGracefulShutdown(cleanup);

  // Keep process alive
  if (config.httpMode) {
    // In HTTP mode, the server keeps the process alive
    console.log(`Server listening on http://localhost:${config.port}`);
    console.log(`Health check available at: http://localhost:${config.port}/health`);
  }
}

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