import "dotenv/config";
import { createApp } from "./app.js";
import { loadConfig } from "./config.js";

try {
  const config = loadConfig();
  const { app } = createApp(config);
  const server = app.listen(config.port, config.host, () => {
    console.log(
      JSON.stringify({
        event: "server_started",
        host: config.host,
        port: config.port,
        mcp_url: config.mcpUrl.href,
      }),
    );
  });

  const shutdown = (signal: string) => {
    console.log(JSON.stringify({ event: "server_stopping", signal }));
    server.close(() => process.exit(0));
    setTimeout(() => process.exit(1), 10_000).unref();
  };
  process.once("SIGINT", () => shutdown("SIGINT"));
  process.once("SIGTERM", () => shutdown("SIGTERM"));
} catch (error) {
  const message = error instanceof Error ? error.message : String(error);
  console.error(JSON.stringify({ event: "startup_failed", message }));
  process.exit(1);
}
