import "dotenv/config";
import path from "node:path";
import { trpcServer } from "@hono/trpc-server";
import { cors } from "hono/cors";
import { createFactory } from "hono/factory";
import { appRouter } from "@/trpc";
import { createContext } from "@/trpc/context";
import { auth } from "./lib/auth";
import type { HonoEnv } from "./lib/types";
import { OnboardRouter } from "./routes/onboard";
import { createServiceContainer } from "./services/setup";
import { formatBytes } from "./utils/formatter";
import { createLogger } from "./utils/logger";

const log = createLogger("Server");
const serviceContainer = createServiceContainer();

const factory = createFactory<HonoEnv>({
	initApp(app) {
		app.use(
			cors({
				origin: [
					process.env.CORS_ORIGIN || "http://localhost:3002",
					"http://localhost:3002",
				],
				credentials: true,
			}),
		);
		app.use((c, next) => {
			c.set("service", serviceContainer);
			return next();
		});
		app.use("/api/auth/*", async (c) => {
			return await auth.handler(c.req.raw);
		});
		app.use(
			"/trpc/*",
			trpcServer({
				router: appRouter,
				createContext: (_opts, context) => {
					return createContext({ context, serviceContainer });
				},
			}),
		);
	},
});

const app = factory
	.createApp()
	.route("/onboard", OnboardRouter)

	.get("/", (c) => {
		return c.text("OK");
	})

	.get("/stats", (c) => {
		const memoryUsage = process.memoryUsage();
		return c.json({
			raw: memoryUsage,
			formatted: {
				rss: formatBytes(memoryUsage.rss),
				heapTotal: formatBytes(memoryUsage.heapTotal),
				heapUsed: formatBytes(memoryUsage.heapUsed),
				external: formatBytes(memoryUsage.external),
				arrayBuffers: formatBytes(memoryUsage.arrayBuffers ?? 0),
			},
		});
	});

// Activate services on startup
serviceContainer.activateService().catch((error) => {
	console.error("Failed to activate services:", error);
	process.exit(1);
});

// Graceful shutdown
process.on("SIGTERM", async () => {
	log.info("SIGTERM received, shutting down gracefully...");
	await serviceContainer.deactivateService();
	process.exit(0);
});

process.on("SIGINT", async () => {
	log.info("SIGINT received, shutting down gracefully...");
	await serviceContainer.deactivateService();
	process.exit(0);
});

export type NontaraApp = typeof app;

Bun.serve({
	port: 3000,
	routes: {
		"/playback/:sessionId/*": {
			GET: (req) => {
				const filePath = req.url.split(req.params.sessionId)[1].split("/");
				// console.log('File path' ,filePath)
				const file = Bun.file(
					path.join(
						process.cwd(),
						"cache",
						"playback",
						req.params.sessionId,
						...filePath,
					),
				);
				if (!file.exists())
					return new Response("Stream file not found.", {
						status: 404,
					});
				const headers = new Headers({
					"Access-Control-Allow-Origin":
						process.env.CORS_ORIGIN || "http://localhost:3001",
				});
				return new Response(file.stream(), {
					headers,
				});
			},
		},
	},
	development: Bun.env.NODE_ENV !== "production",
	fetch: app.fetch,
});

log.info("Started Server on port 3000");
