import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';

const basicIniPath = '/home/nandi/.config/obs-studio/basic/profiles/Untitled/basic.ini';

const streamServer = process.env.OBS_STREAM_SERVER ?? process.env.STREAMPLACE_RTMP_URL ?? '';
const streamKey = process.env.OBS_STREAM_KEY ?? process.env.STREAMPLACE_STREAM_KEY ?? '';

if (!streamServer || !streamKey) {
  console.error('Missing OBS_STREAM_SERVER/STREAMPLACE_RTMP_URL or OBS_STREAM_KEY/STREAMPLACE_STREAM_KEY');
  process.exit(1);
}

let content = '';
try {
  content = readFileSync(basicIniPath, 'utf8');
} catch {
  content = '[General]\nName=Untitled\n';
}

const streamBlock = [
  '[SimpleOutput]',
  'StreamEncoder=obs_x264',
  '[Output]',
  'Mode=Simple',
  '[Stream1]',
  'IgnoreRecommended=false',
  'UseAuth=false',
  'bwtest=false',
  'key=' + streamKey,
  'service=Custom',
  'server=' + streamServer,
].join('\n');

content = content.replace(/\n\[SimpleOutput\][\s\S]*$/m, '');
content = content.replace(/\n\[Output\][\s\S]*$/m, '');
content = content.replace(/\n\[Stream1\][\s\S]*$/m, '');
content = content.trimEnd() + '\n\n' + streamBlock + '\n';

mkdirSync(dirname(basicIniPath), { recursive: true });
writeFileSync(basicIniPath, content);

console.log(basicIniPath);
console.log(JSON.stringify({
  server: streamServer,
  key_present: !!streamKey,
}, null, 2));

