import Fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import fastifyWebsocket from '@fastify/websocket';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { loadConfig } from './config.js';
import { getSql, applySchema, pingDb, closeDb } from './db.js';

import { registerProjectRoutes } from './routes/projects.js';
import { registerSessionRoutes } from './routes/sessions.js';
import { registerSettingsRoutes } from './routes/settings.js';
import { registerMessageRoutes } from './routes/messages.js';
import { registerMessageFeedbackRoutes } from './routes/messages-feedback.js';
import { registerArtifactRoutes } from './routes/artifacts.js';
import { registerChatRoutes } from './routes/chats.js';
import { registerSidebarRoutes } from './routes/sidebar.js';
import { registerWebSocket } from './routes/ws.js';
import { registerCoderProxy } from './routes/coder-proxy.js';
import { registerControlProxy } from './routes/control-proxy.js';
import { registerModelRoutes } from './routes/models.js';
import { registerProviderRoutes } from './routes/providers.js';
import { registerAgentRoutes } from './routes/agents.js';
import { registerSkillsRoutes } from './routes/skills.js';
import { registerTraceRoutes } from './routes/traces.js';
import { registerToolsRoutes } from './routes/tools.js';
import { registerAnalyticsRoutes } from './routes/analytics.js';
import { registerMemoryRoutes } from './routes/memory.js';

import { registerInferenceSettingsRoutes } from './routes/inference-settings.js';
import { createInferenceRunner, runInferenceWithModel } from './services/inference/index.js';
import { createBroker } from './services/broker.js';
import { setBackgroundInferenceEnqueuer } from './services/background-task.js';
import { listSkills } from './services/skills.js';
import * as compaction from './services/compaction.js';
import { configureModelContext } from './services/model-context.js';
import { cleanupTruncations } from './services/truncate.js';
import { loadMcpConfig } from './services/mcp-config.js';
import { initialize as initMcp, getTools as getMcpTools, shutdown as shutdownMcp } from './services/mcp-client.js';
import { appendMcpTools } from './services/tools.js';
import { refreshToolNames } from "./services/agents.js";
import { loadHooksConfig, createHookRunner } from './services/hooks.js';
import { loadLlamaProviders } from './services/llama-providers.js';

async function main() {
  const config = loadConfig();

  // vMultiProvider: load the shared local provider config. When the file is
  // absent, falls back to a single legacy provider from LLAMA_SWAP_URL.
  loadLlamaProviders(config.LLAMA_PROVIDERS_PATH, config.LLAMA_SWAP_URL);

  const app = Fastify({
    logger: { level: config.LOG_LEVEL },
  });

  // Allow empty JSON bodies on POSTs that don't take a body (archive, unarchive, stop, etc.).
  // Default Fastify parser throws FST_ERR_CTP_EMPTY_JSON_BODY on empty string.
  app.removeContentTypeParser(['application/json']);
  app.addContentTypeParser('application/json', { parseAs: 'string' }, (_req, body, done) => {
    const str = (body as string) ?? '';
    if (str.trim().length === 0) {
      done(null, {});
      return;
    }
    try {
      done(null, JSON.parse(str));
    } catch (err) {
      done(err as Error, undefined);
    }
  });

  const sql = getSql(config);
  await applySchema(sql);
  app.log.info('database schema applied');

  const swept = await sql<{ count: string }[]>`
    WITH swept AS (
      UPDATE messages SET status = 'failed'
      WHERE status = 'streaming' AND created_at < NOW() - INTERVAL '5 minutes'
      RETURNING id
    ) SELECT count(*)::text AS count FROM swept
  `;
  const sweptCount = Number(swept[0]?.count ?? 0);
  if (sweptCount > 0) {
    app.log.info({ sweptCount }, 'swept stale streaming messages to failed');
  }

  // v2.x (W3): tell the model-context cache the full config so it can
  // resolve composite model ids through the provider registry. Cache
  // lookups go to <provider.baseUrl>/upstream/<wireModelId>/props to read
  // default_generation_settings.n_ctx — the value persisted as messages.ctx_max.
  configureModelContext(config);

  // v1.15.0-mcp-multi: read MCP config file and connect to all enabled servers.
  // Runs before route registration so the tool list is complete when the first
  // inference request arrives. Per-server graceful degradation: one failing
  // server doesn't block others.
  const mcpConfigPath = config.MCP_CONFIG_PATH ?? '/data/mcp.json';
  const mcpServers = loadMcpConfig(mcpConfigPath, app.log);
  if (mcpServers.length > 0) {
    await initMcp(mcpServers, app.log);
    const mcpTools = getMcpTools();
    if (mcpTools.length > 0) {
      appendMcpTools(mcpTools);
      refreshToolNames();
      app.log.info({ servers: mcpServers.length, tools: mcpTools.length }, 'mcp: registered');
    }
  }
  app.addHook('onClose', async () => { await shutdownMcp(); });


  await app.register(fastifyWebsocket);

  app.get('/api/health', async () => {
    const dbOk = await pingDb(sql);
    return { status: dbOk ? 'ok' : 'degraded', db: dbOk };
  });

  const broker = createBroker(app.log);

  registerProjectRoutes(app, sql, config, broker);
  registerSessionRoutes(app, sql, config, broker);
  registerSettingsRoutes(app, sql);
  registerModelRoutes(app, config);
  registerProviderRoutes(app);
  registerAgentRoutes(app, sql);
  registerSidebarRoutes(app, sql);
  registerChatRoutes(app, sql, broker, config, {
    enqueueCompare: (sessionId, chatId, assistantMessageId, modelOverride, compareGroupId) => {
      // Reuse the inference runner's context pattern for compare mode.
      // Each compare run gets its own AbortController; cancellation keyed by
      // chatId (cancels ALL parallel runs in that compare group).
      let streamSeq = 0;
      const compareCtx: import('./services/inference/types.js').InferenceContext = {
        sql,
        config,
        log: app.log,
        publish: (sid, frame) => {
          frame.stream_seq = streamSeq++;
          broker.publishFrame(sid, frame as import('@boocode/contracts/ws-frames').WsFrame);
        },
        publishUser: (frame) => {
          broker.publishUserFrame('default', frame as import('@boocode/contracts/ws-frames').WsFrame);
        },
        broker,
        hooks: hasHooks ? hookRunner : undefined,
      };
      compareCtx.publishUser({ type: 'chat_status', chat_id: chatId, status: 'streaming', at: new Date().toISOString() });
      void runInferenceWithModel(compareCtx, sessionId, chatId, assistantMessageId, modelOverride, compareGroupId).catch(
        (err: Error) => app.log.error({ err, chatId, modelOverride }, 'compare inference failed'),
      );
    },
    cancelInference: async (_sessionId, chatId) => {
      return inference.cancel(_sessionId, chatId);
    },
    hasActiveInference: (chatId) => inference.hasActive(chatId),
  });
  registerTraceRoutes(app, sql);
  registerMemoryRoutes(app, sql);
  registerToolsRoutes(app, sql);
  registerAnalyticsRoutes(app, sql);
  registerInferenceSettingsRoutes(app);

  // Batch 9.6: warm the skills cache at boot and surface the count. Empty or
  // missing /data/skills is non-fatal — the skill tools just return empty.
  try {
    const skills = await listSkills();
    app.log.info(`skills loaded: ${skills.length}`);
  } catch (err) {
    app.log.warn({ err }, 'skills boot walk failed');
  }

  // vWhale hooks: load hook config and create runner. Missing file = no hooks.
  loadHooksConfig(config.HOOKS_CONFIG_PATH);
  const hookRunner = createHookRunner();
  const hasHooks = Object.keys(loadHooksConfig(config.HOOKS_CONFIG_PATH).hooks).length > 0;

  let streamSeq = 0;
  const inference = createInferenceRunner(
    {
      sql,
      config,
      log: app.log,
      hooks: hasHooks ? hookRunner : undefined,
      publish: (sessionId, frame) => {
        frame.stream_seq = streamSeq++;
        broker.publishFrame(sessionId, frame as import('@boocode/contracts/ws-frames').WsFrame);
      },
      // v1.11: broker handle for compaction.process to publish 'compacted'
      // frames on the per-session channel. Inference's regular publish path
      // is bound to (sessionId, InferenceFrame); compaction publishes a
      // different frame shape, so it goes through the raw broker.
      broker,
    },
    (user, frame) => {
      broker.publishUserFrame(user, frame as import('@boocode/contracts/ws-frames').WsFrame);
    }
  );
  // v2.x: wire the background subagent task system to the inference runner.
  // Tools (spawn_subagent) dispatch fire-and-forget inference via this
  // module-level reference — no import cycle through the tool registry.
  setBackgroundInferenceEnqueuer((sessionId, chatId, assistantId, user) => {
    inference.enqueue(sessionId, chatId, assistantId, user);
  });

  registerMessageRoutes(app, sql, config, broker, {
    enqueueInference: (sessionId, chatId, assistantId, user) => {
      inference.enqueue(sessionId, chatId, assistantId, user);
    },
    // v1.11: synchronous compaction. Awaits the LLM call inside the route's
    // request lifecycle; the new summary row arrives via the WS 'compacted'
    // frame published from inside compaction.process. We let the error
    // bubble up so the route can reply 500 — manual /compact failures
    // should be loud (the user just clicked a button).
    runCompaction: (chatId) =>
      compaction.process({ sql, config, log: app.log, broker, chatId, hooks: hasHooks ? hookRunner : undefined }),
    cancelInference: async (sessionId, chatId) => {
      return inference.cancel(sessionId, chatId);
    },
    hasActiveInference: (chatId) => inference.hasActive(chatId),
    publishUserMessage: (sessionId, chatId, userMessageId, content) => {
      broker.publishFrame(sessionId, {
        type: 'message_started',
        message_id: userMessageId,
        chat_id: chatId,
        role: 'user',
      });
      broker.publishFrame(sessionId, {
        type: 'delta',
        message_id: userMessageId,
        chat_id: chatId,
        content,
      });
      broker.publishFrame(sessionId, {
        type: 'message_complete',
        message_id: userMessageId,
        chat_id: chatId,
      });
    },
    publishMessagesDeleted: (sessionId, chatId, messageIds) => {
      broker.publishFrame(sessionId, {
        type: 'messages_deleted',
        message_ids: messageIds,
        chat_id: chatId,
      });
    },
    publishSessionFrame: (sessionId, frame) => {
      broker.publishFrame(sessionId, frame as import('@boocode/contracts/ws-frames').WsFrame);
    },
  });
  registerMessageFeedbackRoutes(app, sql);
  registerArtifactRoutes(app, sql);
  registerSkillsRoutes(app, sql, {
    enqueueInference: (sessionId, chatId, assistantId, user) => {
      inference.enqueue(sessionId, chatId, assistantId, user);
    },
    publishUserMessage: (sessionId, chatId, userMessageId, content) => {
      broker.publishFrame(sessionId, {
        type: 'message_started',
        message_id: userMessageId,
        chat_id: chatId,
        role: 'user',
      });
      broker.publishFrame(sessionId, {
        type: 'delta',
        message_id: userMessageId,
        chat_id: chatId,
        content,
      });
      broker.publishFrame(sessionId, {
        type: 'message_complete',
        message_id: userMessageId,
        chat_id: chatId,
      });
    },
    publishSessionFrame: (sessionId, frame) => {
      broker.publishFrame(sessionId, frame as import('@boocode/contracts/ws-frames').WsFrame);
    },
  });
  registerWebSocket(app, sql, broker);

  // v2.0.0: reverse proxy /api/coder/* to boocoder (HTTP + WS). CoderPane
  // connects WS through /api/coder/ws/sessions/:id on the same origin.
  const BOOCODER_ORIGIN = process.env.BOOCODER_URL ?? 'http://boocoder:3000';
  registerCoderProxy(app, BOOCODER_ORIGIN);

  // BooControl: reverse proxy /api/control/* to the control host service.
  // Static WS path /api/control/ws (not parameterized per-session like coder-proxy).
  if (process.env.BOOCONTROL_URL) {
    registerControlProxy(app, process.env.BOOCONTROL_URL);
  }

  const webDist = process.env.WEB_DIST_PATH ?? resolve(process.cwd(), '../web/dist');
  if (existsSync(webDist)) {
    await app.register(fastifyStatic, {
      root: webDist,
      prefix: '/',
      wildcard: false,
    });
    app.setNotFoundHandler((req, reply) => {
      if (req.url.startsWith('/api')) {
        reply.code(404).send({ error: 'not found' });
        return;
      }
      reply.sendFile('index.html');
    });
    app.log.info(`serving static frontend from ${webDist}`);
  }

  // v1.13.3: periodic in-process sweeper for streaming rows orphaned by a
  // mid-session crash. The boot sweep (above) only fires once at startup;
  // this loop catches the in-flight case. 60s cadence + 5-min threshold
  // matches the boot sweep so behavior is consistent. Publishes
  // chat_status='idle' on the user channel so the UI dot drops without a
  // refresh — same pattern as handleAbortOrError.
  const SWEEP_INTERVAL_MS = 60_000;
  const sweepStaleStreaming = async (): Promise<void> => {
    try {
      const rows = await sql<{ id: string; chat_id: string }[]>`
        UPDATE messages
        SET status = 'failed', finished_at = clock_timestamp()
        WHERE status = 'streaming'
          AND created_at < NOW() - INTERVAL '5 minutes'
        RETURNING id, chat_id
      `;
      if (rows.length === 0) return;
      app.log.warn(
        { swept: rows.length, ids: rows.map((r) => r.id) },
        'swept stale streaming rows',
      );
      const seenChats = new Set<string>();
      const now = new Date().toISOString();
      for (const row of rows) {
        if (seenChats.has(row.chat_id)) continue;
        seenChats.add(row.chat_id);
        broker.publishUserFrame('default', {
          type: 'chat_status',
          chat_id: row.chat_id,
          status: 'idle',
          at: now,
        });
      }
    } catch (err) {
      app.log.error({ err }, 'stuck-row sweeper failed');
    }
  };
  // v1.13.5: truncation cleanup rides the same cadence — 60s tick reaps
  // tmpfs files past the 7-day TTL plus any orphans whose owning part has
  // been pruned (v1.13.4) or deleted. No-op when the dir is empty.
  const sweepTimer = setInterval(() => {
    void sweepStaleStreaming();
    void cleanupTruncations({ sql, log: app.log });
  }, SWEEP_INTERVAL_MS);
  app.addHook('onClose', async () => { clearInterval(sweepTimer); });

  const shutdown = async (signal: string) => {
    app.log.info(`received ${signal}, shutting down`);
    try {
      await app.close();
      await closeDb();
      process.exit(0);
    } catch (err) {
      app.log.error(err);
      process.exit(1);
    }
  };

  process.on('SIGINT', () => void shutdown('SIGINT'));
  process.on('SIGTERM', () => void shutdown('SIGTERM'));

  // Bound to 0.0.0.0 intentionally. Public access goes through Caddy → Authelia.
  // Direct Tailscale access (100.114.205.53:9500) is unauthenticated by design;
  // the threat model treats Tailnet membership as the trust boundary.
  await app.listen({ port: config.PORT, host: config.HOST });
  app.log.info(`boocode server listening on http://${config.HOST}:${config.PORT}`);
}

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