// Node.js 22+. Usage: node yosemite-api.mjs ./yosemite-peregrines.mp4
// Requires CUEFRAME_API_KEY. Uploading and rendering use cloud credits.
import { readFile, writeFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { randomUUID } from 'node:crypto';

const apiKey = process.env.CUEFRAME_API_KEY;
if (!apiKey || !process.argv[2]) throw new Error('Set CUEFRAME_API_KEY and pass the original Yosemite video path.');
const base = 'https://api.cueframe.ai/v1';
async function checked(url, options) {
  const response = await fetch(url, options);
  if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
  return response;
}
async function api(path, method = 'GET', body, extraHeaders = {}) {
  return checked(base + path, {
    method,
    headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', ...extraHeaders },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
}
async function poll(path, state, success = 'complete') {
  for (let attempt = 0; attempt < 240; attempt++) {
    const item = await (await api(path)).json();
    const status = state(item);
    if (status === success) return item;
    if (['error', 'failed', 'cancelled'].includes(status)) throw new Error(JSON.stringify(item));
    await new Promise(resolve => setTimeout(resolve, 5000));
  }
  throw new Error(`Still processing after 20 minutes. Check ${base + path} before starting another job.`);
}

// 1. Load the public template and upload the original source video.
const template = await (await checked('https://raw.githubusercontent.com/cueframe-ai/cueframe-templates/main/yosemite-peregrines/template.cueframe')).json();
const file = await readFile(process.argv[2]);
const upload = await (await api('/media', 'POST', {
  filename: basename(process.argv[2]), contentType: 'video/mp4', size: file.length,
})).json();
console.log('Media:', upload.id);
await checked(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'video/mp4' }, body: file });
await api(`/media/${upload.id}/finalize`, 'POST', {});
await poll(`/media/${upload.id}`, item => item.processingStatus?.phase);

// 2. Let template preparation bind the source, brand styling and prepared matte.
const job = await (await api(`/templates/${encodeURIComponent(template.slug)}/instantiate`, 'POST', {
  projectName: template.name,
  values: {},
  media: { source: { mediaId: upload.id } },
}, { 'Idempotency-Key': randomUUID() })).json();
console.log('Template job:', job.jobId);
const ready = await poll(`/template-jobs/${job.jobId}`, item => item.status, 'ready');
if (!ready.projectId) throw new Error('Template became ready without a project ID');
console.log('Project:', ready.projectId);
const path = `/projects/${ready.projectId}`;
async function render(filename) {
  const job = await (await api(path + '/renders', 'POST', {})).json();
  console.log('Render:', job.id);
  const completed = await poll(path + '/renders/' + job.id, item => item.status);
  if (!completed.outputUrl) throw new Error('Render completed without an output URL');
  const output = await checked(completed.outputUrl);
  await writeFile(filename, Buffer.from(await output.arrayBuffer()));
  console.log('Saved:', filename);
}
await render('phenomenal.mp4');

// 3. Read the saved composition and its ETag before changing only the title.
const current = await api(path + '/composition');
const etag = current.headers.get('ETag');
if (!etag) throw new Error('Missing composition ETag');
const composition = await current.json();
const title = composition.tracks.flatMap(track => track.contents)
  .find(clip => clip.id === 'peregrines-phenomenal-title');
if (!title) throw new Error('Yosemite title not found');
title.source.params.text = 'EXTRAORDINARY';
const validation = await (await api('/composition/validate', 'POST', composition)).json();
if (!validation.valid) throw new Error(JSON.stringify(validation));
await api(path + '/composition', 'PUT', composition, { 'If-Match': etag });
await render('extraordinary.mp4');
