#!/usr/bin/env bun
import { createProjectManagementApp } from "../../internal/project-management/server.ts";
import { createProjectManagementStore } from "../../internal/project-management/store.ts";

const host = process.env.HWLAB_PROJECT_MANAGEMENT_HOST || "0.0.0.0";
const port = parsePort(process.env.HWLAB_PROJECT_MANAGEMENT_PORT, parsePort(process.env.PORT, 6672));
const store = createProjectManagementStore({ env: process.env });
const app = createProjectManagementApp({ env: process.env, store });

void app.initialize().catch((error) => {
  console.warn(JSON.stringify({
    serviceId: "hwlab-project-management",
    event: "project-management-startup-initialize-failed",
    code: error?.code ?? "project_management_initialize_failed",
    message: error?.message ?? String(error)
  }));
});

const runtime = Bun.serve({
  hostname: host,
  port,
  fetch: (request) => app.fetch(request)
});

process.stdout.write(`${JSON.stringify({
  serviceId: "hwlab-project-management",
  status: "listening",
  host,
  port: runtime.port,
  routes: [
    "/health/live",
    "/health/ready",
    "/v1/project-management/navigation",
    "/v1/project-management/projects",
    "/v1/project-management/mdtodo/sources",
    "/v1/project-management/mdtodo/files",
    "/v1/project-management/mdtodo/tasks",
    "GET /v1/project-management/workbench-links",
    "POST /v1/project-management/workbench-links"
  ]
})}\n`);

for (const signal of ["SIGINT", "SIGTERM"]) {
  process.on(signal, async () => {
    runtime.stop(true);
    await app.close();
    process.exit(0);
  });
}

function parsePort(value: unknown, fallback: number): number {
  const parsed = Number.parseInt(String(value ?? ""), 10);
  return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : fallback;
}
