import { Livestream } from "../lib/models.js";
import { knex } from "../lib/ormish.js";
import assert from "assert";
import { glob }  from "../lib/builderator.js";
import { video_meta, upsert_media } from "./media.js";

export const description = "Process Livestreams from the database and load the media.";

const load_livestreams = async () => {
  const media_files = glob("./media/videos/livestreams/*.mp4");
  const id_match = /.*Livestream_([0-9][0-9]).*/

  for(let fname of media_files) {
    const video = await video_meta({src: fname.slice(1)});

    const stream_id = fname.match(id_match)[1];
    assert(stream_id, `File ${fname} does not have a Livestream_ID format.`);

    // use the episode number since ID could not represent the sequence
    const stream = await Livestream.first({episode: stream_id});

    if(stream === undefined) {
      console.error(`SKIP! File ${fname} does not have a Livestream with ID ${stream_id}`);
    } else {
      console.log("MEDIA", fname, "STREAM ID", stream.id, stream.title);

      // normally this works with .md files so fix it up
      video.title = stream.title;

      const media = await upsert_media(video, stream.description);
      assert(media !== undefined, `Failed to upsert media for ${fname}.`);

      await Livestream.update({id: stream.id}, {
        media_id: media.id,
        state: "archived",
        poster: media.poster
      });
    }
  }
}

export const main = async () => {
  await load_livestreams();
  knex.destroy();
}
