#!/usr/bin/env node

/**
 * Google Search Console MCP Server
 * Entry point - initializes auth, client, and server
 */

import { getAuthClient } from './auth/index.js';
import { GSCClient } from './lib/gsc-client.js';
import { Cache } from './lib/cache.js';
import { RateLimiter } from './lib/rate-limit.js';
import { GSCServer } from './server.js';

async function main() {
  try {
    console.error('Starting Google Search Console MCP server...');

    // Initialize authentication
    console.error('Authenticating...');
    const authClient = await getAuthClient();

    // Initialize GSC client
    const gscClient = new GSCClient(authClient as any);

    // Initialize cache
    const cacheTTL = process.env.GSC_CACHE_TTL 
      ? parseInt(process.env.GSC_CACHE_TTL) * 1000 
      : undefined;
    
    const cache = new Cache({
      analyticsTTL: cacheTTL
    });

    // Initialize rate limiter
    const rateLimiter = new RateLimiter();

    // Start periodic cache pruning
    setInterval(() => {
      cache.prune();
    }, 5 * 60 * 1000); // Every 5 minutes

    // Create and connect server
    const server = new GSCServer({
      gscClient,
      cache,
      rateLimiter
    });

    await server.connect();

    // Handle graceful shutdown
    process.on('SIGINT', () => {
      console.error('Shutting down gracefully...');
      process.exit(0);
    });

    process.on('SIGTERM', () => {
      console.error('Shutting down gracefully...');
      process.exit(0);
    });

  } catch (error: any) {
    console.error('Fatal error:', error.message);
    console.error(error.stack);
    process.exit(1);
  }
}

main();
