import * as fs from 'fs/promises';
import { promisify } from 'util';
import { exec } from 'child_process';

const execPromise = promisify(exec);

const VIDEOS_PATH = 'static/videos/';

/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
  const files = await fs.readdir(VIDEOS_PATH);

  const fileMetadata = await Promise.all(files.map(async (v) => {
    const path = VIDEOS_PATH + v;
    const stat = await fs.stat(path);
    const vidInfo = JSON.parse((await execPromise(`ffprobe -v error -select_streams v -show_entries stream=width,height -of json '${path}'`)).stdout);
    const mime = (await execPromise(`file '${path}' --mime-type -b`)).stdout.trim();
    return {
      modified: stat.mtimeMs,
      ...vidInfo.streams[0],
      name: v,
      mime: mime
    };
  }));

  const sorted = fileMetadata.sort((a, b) => a.modified - b.modified).map(a => ({width: a.width, height: a.height, name: a.name, mime: a.mime}));

  return sorted;
}