import NodeMediaServer from "node-media-server";
import path from "path";

let nms: NodeMediaServer | null = null;

const config = {
  rtmp: {
    port: 1935, // Standard RTMP port
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60,
    listen: "0.0.0.0", // Bind to all interfaces
  },
  http: {
    port: 8000,
    mediaroot: path.join(process.cwd(), "media"),
    allow_origin: "*",
  },
  logType: 3, // Enable verbose logging
};

export function startRTMPServer() {
  if (!nms) {
    try {
      console.log(
        "Starting RTMP server with config:",
        JSON.stringify(config, null, 2)
      );
      console.log("Process environment:", {
        REPL_SLUG: process.env.REPL_SLUG,
        REPL_OWNER: process.env.REPL_OWNER,
        NODE_ENV: process.env.NODE_ENV,
      });

      nms = new NodeMediaServer(config);

      // Assign event handlers as properties per the new API
      nms.onError = (err: any) => {
        console.error("RTMP Server Error:", err);
      };

      nms.onListening = () => {
        console.log(`RTMP Server is listening on port ${config.rtmp.port}`);
        console.log(
          `RTMP URL: rtmp://${process.env.REPL_SLUG}.${process.env.REPL_OWNER}.repl.co/live`
        );
      };

      nms.onPreConnect = (id: string, args: any) => {
        console.log(
          "[NodeEvent on preConnect]",
          `id=${id} args=${JSON.stringify(args)}`
        );
      };

      nms.onPostConnect = (id: string, args: any) => {
        console.log(
          "[NodeEvent on postConnect]",
          `id=${id} args=${JSON.stringify(args)}`
        );
      };

      nms.onDoneConnect = (id: string, args: any) => {
        console.log(
          "[NodeEvent on doneConnect]",
          `id=${id} args=${JSON.stringify(args)}`
        );
      };

      nms.onPrePublish = (id: string, streamPath: string, args: any) => {
        console.log(
          "[NodeEvent on prePublish]",
          `id=${id} streamPath=${streamPath} args=${JSON.stringify(args)}`
        );
      };

      nms.onPostPublish = (id: string, streamPath: string, args: any) => {
        console.log(
          "[NodeEvent on postPublish]",
          `id=${id} streamPath=${streamPath} args=${JSON.stringify(args)}`
        );
      };

      nms.onDonePublish = (id: string, streamPath: string, args: any) => {
        console.log(
          "[NodeEvent on donePublish]",
          `id=${id} streamPath=${streamPath} args=${JSON.stringify(args)}`
        );
      };

      nms.onClientError = (id: string, err: any) => {
        console.error("[NodeEvent on clientError]", `id=${id}`, err);
      };

      nms.run();
      console.log("RTMP Server started successfully");
      return true;
    } catch (error) {
      console.error("Failed to start RTMP server:", error);
      return false;
    }
  }
  return false;
}

export async function stopRTMPServer() {
  if (nms) {
    try {
      // Call the built-in stop method (which should gracefully close all servers)
      await nms.stop();
      nms = null;
      console.log("RTMP Server stopped successfully");
      return true;
    } catch (error) {
      console.error("Failed to stop RTMP server:", error);
      nms = null;
      return false;
    }
  }
  return false;
}

export function isRTMPServerRunning() {
  return nms !== null;
}