import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import './db.js'; // importing db runs migrate()
import { db } from './db.js';
import { seed } from './seed.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';

// Seed canonical cards on boot.
seed();

// 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 result = db
    .prepare("UPDATE agent_runs SET status = 'stopped', finished_at = COALESCE(finished_at, ?), error = COALESCE(error, 'interrupted by server restart') WHERE status IN ('running', 'queued')")
    .run(now);
  if (result.changes > 0) {
    console.log(`[api] reconciled ${result.changes} 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);

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