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

const scenePath = '/home/nandi/.config/obs-studio/basic/scenes/Untitled.json';
const textSourceName = process.env.OBS_TEXT_INPUT_NAME ?? 'Agent Reply';
const sceneName = process.env.OBS_SCENE_NAME ?? 'Scene';

const scene = JSON.parse(readFileSync(scenePath, 'utf8')) as any;
scene.current_scene = sceneName;
scene.current_program_scene = sceneName;

const sources = Array.isArray(scene.sources) ? scene.sources : [];
const sceneSource = sources.find((s: any) => s.name === sceneName && s.id === 'scene');

const hasTextSource = sources.some((s: any) => s.name === textSourceName);
if (!hasTextSource) {
  sources.push({
    prev_ver: 536936450,
    name: textSourceName,
    uuid: '11111111-2222-3333-4444-555555555555',
    id: 'text_ft2_source',
    versioned_id: 'text_ft2_source',
    settings: {
      text: '',
    },
    mixers: 0,
    sync: 0,
    flags: 0,
    volume: 1.0,
    balance: 0.5,
    enabled: true,
    muted: false,
    'push-to-mute': false,
    'push-to-mute-delay': 0,
    'push-to-talk': false,
    'push-to-talk-delay': 0,
    hotkeys: {},
    deinterlace_mode: 0,
    deinterlace_field_order: 0,
    monitoring_type: 0,
    private_settings: {},
  });
}

if (sceneSource && Array.isArray(sceneSource.settings?.items)) {
  const alreadyPlaced = sceneSource.settings.items.some((item: any) => item.name === textSourceName);
  if (!alreadyPlaced) {
    sceneSource.settings.items.push({
      name: textSourceName,
      source_uuid: '11111111-2222-3333-4444-555555555555',
      visible: true,
      locked: false,
      pos: { x: 40.0, y: 40.0 },
      scale: { x: 1.0, y: 1.0 },
      align: 5,
      bounds_type: 0,
      bounds_align: 0,
      crop_left: 0,
      crop_top: 0,
      crop_right: 0,
      crop_bottom: 0,
      id: 1,
      group_item_backup: false,
    });
  }
}

scene.sources = sources;
mkdirSync(dirname(scenePath), { recursive: true });
writeFileSync(scenePath, JSON.stringify(scene, null, 4) + '\n');

console.log(scenePath);
console.log(JSON.stringify({ sceneName, textSourceName }, null, 2));
