import { serve } from '@hono/node-server';
import { loadConfig, type Config } from './config.js';
import { createRouter } from './api/router.js';
import { createLogger } from './utils/logger.js';
import { resolve } from 'path';

export interface ServerOptions {
  host?: string;
  port?: number;
  repoRoot?: string;
}

/**
 * Start the emdash-core-ts server
 */
export async function startServer(options: ServerOptions = {}) {
  // Load configuration with overrides
  const config = loadConfig({
    host: options.host,
    port: options.port,
    repoRoot: options.repoRoot,
  });

  const logger = createLogger({
    name: 'server',
    level: config.logLevel,
  });

  // Resolve repository root
  const repoRoot = resolve(config.repoRoot ?? process.cwd());

  // Create the router
  const app = createRouter({ config, repoRoot });

  logger.info(
    {
      host: config.host,
      port: config.port,
      repoRoot,
      defaultModel: config.defaultModel,
    },
    'Starting emdash-core-ts server'
  );

  // Start the server
  const server = serve({
    fetch: app.fetch,
    hostname: config.host,
    port: config.port,
  });

  logger.info(`Server running at http://${config.host}:${config.port}`);

  // Handle graceful shutdown
  const shutdown = () => {
    logger.info('Shutting down server...');
    server.close(() => {
      logger.info('Server stopped');
      process.exit(0);
    });
  };

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

  return { app, server, config };
}

/**
 * CLI entry point
 */
async function main() {
  // Parse CLI arguments
  const args = process.argv.slice(2);
  const options: ServerOptions = {};

  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    const next = args[i + 1];

    switch (arg) {
      case '--host':
      case '-h':
        options.host = next;
        i++;
        break;
      case '--port':
      case '-p':
        options.port = parseInt(next, 10);
        i++;
        break;
      case '--repo':
      case '-r':
        options.repoRoot = next;
        i++;
        break;
      case '--help':
        console.log(`
emdash-core-ts - TypeScript agent server

Usage:
  emdash-core-ts [options]

Options:
  --host, -h <host>    Server host (default: 127.0.0.1)
  --port, -p <port>    Server port (default: 8765)
  --repo, -r <path>    Repository root path (default: cwd)
  --help               Show this help message

Environment Variables:
  EMDASH_HOST          Server host
  EMDASH_PORT          Server port
  EMDASH_DEFAULT_MODEL Default LLM model
  ANTHROPIC_API_KEY    Anthropic API key
  OPENAI_API_KEY       OpenAI API key
`);
        process.exit(0);
    }
  }

  try {
    await startServer(options);
  } catch (err) {
    console.error('Failed to start server:', err);
    process.exit(1);
  }
}

// Run if this is the entry point
const isMain = import.meta.url === `file://${process.argv[1]}`;
if (isMain) {
  main();
}
