import { createRequire } from "module";
const require = createRequire(import.meta.url);

const NodeMediaServer = require("node-media-server");
import path from "path";

let nms: any = null;
let isRunning = false;

const config = {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60,
    listen: "0.0.0.0",
  },
  http: {
    port: 8001,
    mediaroot: path.join(process.cwd(), "media"),
    allow_origin: "*",
    api: true,  // ✅ Add this to enable API
  },
};

export function startRTMPServer() {
  try {
    if (isRunning && nms) {
      console.log("[RTMP] Server is already running");
      return true;
    }

    console.log("[RTMP] Starting server...");
    nms = new NodeMediaServer(config);
    nms.run();
    isRunning = true;
    console.log("[RTMP] Server started on port", config.rtmp.port);
    return true;
  } catch (error) {
    console.error("[RTMP] Error starting server:", error);
    isRunning = false;
    nms = null;
    return false;
  }
}

export function stopRTMPServer() {
  if (nms && isRunning) {
    try {
      nms.stop();
      isRunning = false;
      nms = null;
      console.log("[RTMP] Server stopped");
      return true;
    } catch (error) {
      console.error("[RTMP] Error stopping server:", error);
      isRunning = false;
      nms = null;
      return false;
    }
  }
  return false;
}

export function isRTMPServerRunning(): boolean {
  return isRunning && nms !== null;
}

export function getRTMPUrl(sessionId: number | string): string {
  const baseURL = process.env.RTMP_SERVER_URL || "confapp.co";
  return `rtmp://${baseURL}:1935/live/${sessionId}`;
}

export function isStreamActive(sessionId: number | string): boolean {
  try {
    if (!nms || !isRunning) {
      console.log("[RTMP] Server not running");
      return false;
    }

    // The stream path we're looking for
    const streamKey = typeof sessionId === 'number' ? sessionId : sessionId.toString();
    const streamPath = `/live/${streamKey}`;

    // Check for active publishers in nms.publishers
    if (nms.publishers) {
      for (let publisherId in nms.publishers) {
        const publisher = nms.publishers[publisherId];
        if (publisher && publisher.streamPath === streamPath) {
          console.log(`[RTMP] Found active publisher for stream path: ${streamPath}`);
          return true;
        }
      }
    }

    // Also check the regular expression format used by node-media-server
    const regexPath = new RegExp(`\\/live\\/${streamKey}$`);
    if (nms.sessions) {
      for (let sessionId in nms.sessions) {
        const session = nms.sessions[sessionId];
        if (session && session.publishStreamPath && regexPath.test(session.publishStreamPath)) {
          console.log(`[RTMP] Found active session for stream path: ${streamPath}`);
          return true;
        }
      }
    }

    console.log(`[RTMP] No active stream found for path: ${streamPath}`);
    return false;
  } catch (error) {
    console.error(`[RTMP] Error checking stream status:`, error);
    return false;
  }
}