import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';

export type DemoRoom = {
  id: string;
  roomTitle: string;
  categoryBadge: string;
  sessions: {
    start: string;
    end: string;
    mainTheme: string;
    subThemes: { title: string; speaker: string }[];
  }[];
};

export function loadDemoRooms(): DemoRoom[] {
  // Evaluate only the bundled demo source; never read a browser's localStorage.
  const source = readFileSync(new URL('../data-jadwal.js', import.meta.url), 'utf8');
  const json: string = runInNewContext(`${source}\nJSON.stringify(DEFAULT_SIGNAGE_ROOMS)`, {}, { timeout: 1000 });
  return Object.values(JSON.parse(json) as Record<string, DemoRoom>);
}

export function parseEventDate(value: string | undefined): Date {
  if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
    throw new Error('Set SEED_EVENT_DATE to an explicit WIB calendar date (YYYY-MM-DD).');
  }
  const date = new Date(`${value}T00:00:00.000Z`);
  if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== value || value.startsWith('0000')) {
    throw new Error('SEED_EVENT_DATE must be a valid calendar date.');
  }
  // Prisma represents a MySQL DATE using the UTC midnight of that date.
  return date;
}

export function jakartaTimestamp(date: string, time: string): Date {
  parseEventDate(date);
  if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) throw new Error(`Invalid demo time: ${time}`);
  return new Date(`${date}T${time}:00+07:00`);
}

export function splitSpeaker(value: string): { name: string; institution: string | null } {
  const match = value.trim().match(/^(.+)\s+\(([^()]*)\)$/);
  return match
    ? { name: match[1].trim(), institution: match[2].trim() || null }
    : { name: value.trim(), institution: null };
}
