import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import type { Server as HttpServer } from 'node:http';
import './db.js'; // importing db runs migrate()
import { db } from './db.js';
import { appendRunEvent } from './orchestrator/events.js';
import { kanban } from './routes/kanban.js';
import { pages } from './routes/pages.js';
import { orchestrator } from './routes/orchestrator.js';
import { internal } from './routes/internal.js';

// Reconcile orchestrator runs orphaned by a previous process: anything still
// marked running/queued has no live subprocess, so mark it stopped.
{
  const now = new Date().toISOString();
  const orphans = db
    .prepare("SELECT id FROM agent_runs WHERE status IN ('running', 'queued')")
    .all() as { id: string }[];
  for (const { id } of orphans) {
    db.prepare(
      "UPDATE agent_runs SET status = 'stopped', finished_at = COALESCE(finished_at, ?), error = COALESCE(error, 'interrupted by server restart') WHERE id = ?",
    ).run(now, id);
    // Emit a persisted status event so an open/reconnecting SSE stream replays
    // the terminal state last — otherwise its history replay would re-assert the
    // stale `running` status and leave the UI stuck mid-run.
    appendRunEvent(id, 'status', { status: 'stopped' });
    appendRunEvent(id, 'log', { level: 'warn', text: 'interrupted by server restart' });
  }
  if (orphans.length > 0) {
    console.log(`[api] reconciled ${orphans.length} interrupted agent run(s) → stopped`);
  }
}

const app = new Hono();

app.get('/api/health', (c) => c.json({ ok: true }));
app.route('/api/kanban', kanban);
app.route('/api/pages', pages);
app.route('/api/orchestrator', orchestrator);
app.route('/api/internal', internal);

const port = Number(process.env.PORT ?? 3001);

const server = serve({ fetch: app.fetch, port }, (info) => {
  console.log(`[api] VOID::NAV Kanban API on http://localhost:${info.port}`);
}) as unknown as HttpServer;

// Merge-all can block for many minutes while conflict-resolution agents work;
// disable Node's default request/socket timeouts so those long requests survive.
server.requestTimeout = 0;
server.headersTimeout = 0;
server.setTimeout(0);
