import { readFileSync, statSync } 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: {},
};

try {
  statSync(COMPOSITION_PATH);
} catch {
  process.exit(0);
}

let code;
try {
  code = readFileSync(COMPOSITION_PATH, "utf-8");
} catch {
  process.exit(0);
}

if (!code.trim() || !code.includes("MyComposition")) {
  process.exit(0);
}

let transpiled;
try {
  transpiled = transform(code, {
    presets: ["react"],
    filename: "composition.jsx",
  }).code;
} catch (e) {
  process.stderr.write(
    `VALIDATION_FAILED: JSX transpilation error: ${e.message}\nFix the code in /home/ccapi/project/composition.jsx and try again.\n`,
  );
  process.exit(2);
}

let makeComponent;
try {
  makeComponent = new Function(
    "React",
    "AbsoluteFill",
    "useCurrentFrame",
    "interpolate",
    "useVideoConfig",
    transpiled + "\nreturn MyComposition;",
  );
} catch (e) {
  process.stderr.write(
    `VALIDATION_FAILED: Code evaluation error: ${e.message}\nFix the code in /home/ccapi/project/composition.jsx and try again.\n`,
  );
  process.exit(2);
}

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) {
  process.stderr.write(
    `VALIDATION_FAILED:\n${errors.join("\n")}\nFix the code in /home/ccapi/project/composition.jsx and try again.\n`,
  );
  process.exit(2);
}

process.exit(0);
