export type MediaMode = 'legacy' | 'single_server_sfu';

const parseMediaMode = (value: string | undefined): MediaMode => {
  const normalized = (value ?? 'legacy').trim().toLowerCase();
  if (normalized === 'single_server_sfu') {
    return 'single_server_sfu';
  }
  return 'legacy';
};

const parseCsv = (value: string | undefined): string[] => {
  if (!value) return [];
  return value
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
};

const parsePositiveNumber = (value: string | undefined): number | null => {
  if (!value) return null;
  const parsed = Number(value);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return null;
  }
  return parsed;
};

export const parseFeatureFlag = (value: string | undefined, defaultValue: boolean): boolean => {
  if (value === undefined) {
    return defaultValue;
  }

  const normalized = value.trim().toLowerCase();
  if (['1', 'true', 'yes', 'on'].includes(normalized)) {
    return true;
  }
  if (['0', 'false', 'no', 'off'].includes(normalized)) {
    return false;
  }
  return defaultValue;
};

export const mediaMode: MediaMode = parseMediaMode(process.env.MEDIA_MODE);
export const simpleStreamingEnabled = parseFeatureFlag(process.env.SIMPLE_STREAMING, false);
export const streamRecordingEnabled = parseFeatureFlag(process.env.STREAM_RECORDINGS_ENABLED, false);

export const mediaConfig = {
  mode: mediaMode,
  simpleStreamingEnabled,
  streamRecordingEnabled,
  turn: {
    urls: parseCsv(process.env.TURN_URLS),
    username: process.env.TURN_USERNAME ?? '',
    credential: process.env.TURN_CREDENTIAL ?? '',
  },
  recordingsDir: process.env.MEDIA_RECORDINGS_DIR ?? 'media-recordings',
  limits: {
    maxPublishers: parsePositiveNumber(process.env.MEDIA_MAX_PUBLISHERS),
    maxSubscribersPerRoom: parsePositiveNumber(process.env.MEDIA_MAX_SUBSCRIBERS_PER_ROOM),
  },
};
