import { Hono } from 'hono';
import { logger as honoLogger } from 'hono/logger';
import { healthRoutes } from './routes/health.js';
import { dbRoutes } from './routes/db.js';
import { indexRoutes } from './routes/index-routes.js';
import { searchRoutes } from './routes/search.js';
import { queryRoutes } from './routes/query.js';
import { contextRoutes } from './routes/context.js';
import { verifyRoutes } from './routes/verify.js';
import { skillsRoutes } from './routes/skills.js';
import { rulesRoutes } from './routes/rules.js';
import { authRoutes } from './routes/auth.js';
import { planRoutes } from './routes/plan.js';
import { agentRoutes } from './agent.js';
import { errorHandler } from './middleware/error.js';
import { corsMiddleware } from './middleware/cors.js';
import type { Config } from '../config.js';
import type { KuzuConnection } from '../graph/connection.js';
import type { EmbeddingService } from '../embeddings/service.js';

/**
 * Application context stored in Hono context
 */
export interface AppContext {
  Variables: {
    config: Config;
    repoRoot: string;
    conn?: KuzuConnection;
    embeddings?: EmbeddingService;
  };
}

/**
 * Router creation options
 */
export interface RouterOptions {
  config: Config;
  repoRoot: string;
  conn?: KuzuConnection;
  embeddings?: EmbeddingService;
}

/**
 * Create the main Hono router
 */
export function createRouter(options: RouterOptions): Hono<AppContext> {
  const app = new Hono<AppContext>();

  // Global middleware
  app.use('*', corsMiddleware);
  app.use('*', honoLogger());

  // Error handler
  app.onError(errorHandler);

  // Store context in request
  app.use('*', async (c, next) => {
    c.set('config', options.config);
    c.set('repoRoot', options.repoRoot);
    if (options.conn) {
      c.set('conn', options.conn);
    }
    if (options.embeddings) {
      c.set('embeddings', options.embeddings);
    }
    await next();
  });

  // Health and monitoring
  app.route('/health', healthRoutes);

  // Database management
  app.route('/db', dbRoutes);

  // Indexing and ingestion
  app.route('/index', indexRoutes);

  // Search
  app.route('/search', searchRoutes);

  // Graph queries
  app.route('/query', queryRoutes);

  // Context management
  app.route('/context', contextRoutes);

  // Verification
  app.route('/verify', verifyRoutes);

  // Skills
  app.route('/skills', skillsRoutes);

  // Rules
  app.route('/rules', rulesRoutes);

  // Auth
  app.route('/auth', authRoutes);

  // Planning
  app.route('/plan', planRoutes());

  // Agent
  app.route('/agent', agentRoutes);

  // Root endpoint
  app.get('/', (c) => {
    return c.json({
      name: 'emdash-core-ts',
      version: '0.1.0',
      endpoints: {
        health: '/health',
        db: '/db',
        index: '/index',
        search: '/search',
        query: '/query',
        context: '/context',
        verify: '/verify',
        skills: '/skills',
        rules: '/rules',
        auth: '/auth',
        plan: '/plan',
        agent: '/agent',
      },
    });
  });

  // 404 handler
  app.notFound((c) => {
    return c.json(
      {
        error: 'NotFound',
        message: `Route ${c.req.method} ${c.req.path} not found`,
      },
      404
    );
  });

  return app;
}
