import { readFileSync } from "node:fs";
import { transform } from "@babel/standalone";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { AbsoluteFill, interpolate } from "remotion";

const COMPOSITION_PATH = "/home/ccapi/project/composition.jsx";
const FRAMES_TO_TEST = [0, 30, 60, 90, 119];
const VIDEO_CONFIG = {
  width: 1280,
  height: 720,
  fps: 30,
  durationInFrames: 120,
  id: "MyComp",
  defaultProps: {},
};

let code;
try {
  code = readFileSync(COMPOSITION_PATH, "utf-8");
} catch (e) {
  console.error("VALIDATION_FAILED");
  console.error(`Cannot read ${COMPOSITION_PATH}: ${e.message}`);
  process.exit(1);
}

let transpiled;
try {
  transpiled = transform(code, {
    presets: ["react"],
    filename: "composition.jsx",
  }).code;
} catch (e) {
  console.error("VALIDATION_FAILED");
  console.error(`JSX transpilation error: ${e.message}`);
  process.exit(1);
}

let makeComponent;
try {
  makeComponent = new Function(
    "React",
    "AbsoluteFill",
    "useCurrentFrame",
    "interpolate",
    "useVideoConfig",
    transpiled + "\nreturn MyComposition;",
  );
} catch (e) {
  console.error("VALIDATION_FAILED");
  console.error(`Code evaluation error: ${e.message}`);
  process.exit(1);
}

const errors = [];

for (const frame of FRAMES_TO_TEST) {
  const mockUseCurrentFrame = () => frame;
  const mockUseVideoConfig = () => VIDEO_CONFIG;

  try {
    const Component = makeComponent(
      React,
      AbsoluteFill,
      mockUseCurrentFrame,
      interpolate,
      mockUseVideoConfig,
    );

    if (typeof Component !== "function") {
      errors.push(
        `Frame ${frame}: MyComposition is not a valid React component`,
      );
      continue;
    }

    const html = renderToStaticMarkup(React.createElement(Component));

    if (!html || html.length === 0) {
      errors.push(`Frame ${frame}: rendered empty output`);
    }
  } catch (e) {
    errors.push(`Frame ${frame}: ${e.message}`);
  }
}

if (errors.length > 0) {
  console.error("VALIDATION_FAILED");
  errors.forEach((e) => console.error(e));
  process.exit(1);
}

console.log("VALIDATION_OK");
console.log(`Tested frames: ${FRAMES_TO_TEST.join(", ")}`);
console.log("All frames rendered successfully");
