import { file } from "bun";
import { join, resolve } from "path";

export interface YtdlpConfig {
  enabled: boolean;
  command: string;
  ffmpegCommand: string;
  updateCommand: string | null;
  fastQueueConcurrent: number;
  slowQueueInterval: number;
  allowPlaylists: boolean;
  autoUpdate: boolean;
  updateCheckInterval: number;
}

export interface ReplayGainConfig {
  enabled: boolean;
  command: string;
  truePeak: boolean;
  timeoutMs: number;
  maxConcurrent?: number;
  maxOutputBytes?: number;
}

export interface Config {
  port: number;
  musicDir: string;
  allowGuests: boolean;
  defaultPermissions: string[];
  ytdlp?: YtdlpConfig;
  replayGain?: ReplayGainConfig;
}

const CONFIG_PATH = join(import.meta.dir, "config.json");

export const DEFAULT_CONFIG: Config = {
  port: 3001,
  musicDir: "./music",
  allowGuests: true,
  defaultPermissions: ["listen", "control"],
  ytdlp: {
    enabled: false,
    command: "yt-dlp",
    ffmpegCommand: "ffmpeg",
    updateCommand: "yt-dlp -U",
    fastQueueConcurrent: 2,
    slowQueueInterval: 180,
    allowPlaylists: true,
    autoUpdate: true,
    updateCheckInterval: 86400
  },
  replayGain: {
    enabled: true,
    command: "rsgain",
    truePeak: false,
    timeoutMs: 120000,
    maxConcurrent: 1,
    maxOutputBytes: 262144
  }
};

// Create default config if missing
const configFile = file(CONFIG_PATH);
if (!(await configFile.exists())) {
  console.log("[Config] Creating default config.json...");
  await Bun.write(CONFIG_PATH, JSON.stringify(DEFAULT_CONFIG, null, 2));
  console.log("Config created at config.json. Have a look at it then restart the server. Bye!");
  process.exit();
}

export const config: Config = await configFile.json();

export const MUSIC_DIR = resolve(import.meta.dir, config.musicDir);
export const PUBLIC_DIR = join(import.meta.dir, "public");

console.log(`Config loaded: port=${config.port}, musicDir=${MUSIC_DIR}, allowGuests=${config.allowGuests}`);
