#!/usr/bin/env bun
import { createTaskTreeDispatcher } from "../../internal/tasktree/dispatcher.ts";
import { createTaskTreeHttpApp } from "../../internal/tasktree/http.ts";
import { taskTreeRuntime } from "../../internal/tasktree/runtime.ts";

const runtime = taskTreeRuntime({
  ...process.env,
  TASKTREE_BACKUP_WORKTREE: process.env.TASKTREE_BACKUP_WORKTREE ?? ".state/tasktree/backup-repo-api",
});
const dispatch = createTaskTreeDispatcher(runtime);
const app = createTaskTreeHttpApp({ dispatch, close: () => runtime.store.close() });
const host = process.env.TASKTREE_API_HOST || "0.0.0.0";
const port = Number.parseInt(process.env.TASKTREE_API_PORT || process.env.PORT || "6673", 10);
const server = Bun.serve({ hostname: host, port, fetch: (request) => app.fetch(request) });

process.stdout.write(`${JSON.stringify({ serviceId: "hwlab-tasktree-api", status: "listening", host, port: server.port })}\n`);
for (const signal of ["SIGINT", "SIGTERM"] as const) {
  process.once(signal, async () => {
    server.stop(true);
    await app.close();
    process.exit(0);
  });
}
