import "server-only";

import path from "node:path";

import { resolveMediaBinaryPath, type BinaryResolutionSource } from "@/lib/server/binary-paths";

function parsePositiveInteger(rawValue: string | undefined, fallbackValue: number) {
  if (!rawValue) {
    return fallbackValue;
  }

  const parsedValue = Number(rawValue);
  if (!Number.isFinite(parsedValue) || parsedValue <= 0) {
    return fallbackValue;
  }

  return Math.floor(parsedValue);
}

export interface MediaProcessingConfig {
  ffmpegPath: string;
  ffprobePath: string;
  ffmpegSource: BinaryResolutionSource;
  ffprobeSource: BinaryResolutionSource;
  tempRootDirectory: string;
  uploadsDirectory: string;
  outputsDirectory: string;
  maxUploadSizeBytes: number;
  maxCommandDurationMs: number;
  cleanupMaxAgeMs: number;
}

let cachedConfig: MediaProcessingConfig | null = null;

export function getMediaProcessingConfig(): MediaProcessingConfig {
  if (cachedConfig) {
    return cachedConfig;
  }

  const tempRootDirectory = path.resolve(
    process.env.VIDEO_HAUS_TEMP_ROOT || path.join(process.cwd(), ".tmp", "media")
  );
  const uploadsDirectory = path.join(tempRootDirectory, "uploads");
  const outputsDirectory = path.join(tempRootDirectory, "outputs");
  const ffmpeg = resolveMediaBinaryPath("ffmpeg");
  const ffprobe = resolveMediaBinaryPath("ffprobe");

  cachedConfig = {
    ffmpegPath: ffmpeg.path,
    ffprobePath: ffprobe.path,
    ffmpegSource: ffmpeg.source,
    ffprobeSource: ffprobe.source,
    tempRootDirectory,
    uploadsDirectory,
    outputsDirectory,
    maxUploadSizeBytes: parsePositiveInteger(process.env.VIDEO_HAUS_MAX_UPLOAD_SIZE_BYTES, 1_000_000_000),
    maxCommandDurationMs: parsePositiveInteger(process.env.VIDEO_HAUS_COMMAND_TIMEOUT_MS, 120_000),
    cleanupMaxAgeMs: parsePositiveInteger(process.env.VIDEO_HAUS_CLEANUP_MAX_AGE_MS, 1_800_000)
  };

  return cachedConfig;
}
