import { stableSegmentStateKey } from '../segment-state.js';
import { STAR_CRAWL_REDRAW_KEYFRAME_PARAMS } from './procedural-keyframes.js';
import {
  ensureStarCrawlFont,
  renderStarCrawlTextureCanvas,
} from './star-crawl.js?v=8';

const redrawParameters = new Set(STAR_CRAWL_REDRAW_KEYFRAME_PARAMS);

export function starCrawlTextureIsAnimated(
  track,
  segment,
  segmentIndex,
  keyframeData = {},
  lfoData = {},
) {
  const stateKey = stableSegmentStateKey(
    'scenes',
    track?.id,
    segment,
    segmentIndex,
  );
  const keyframes = keyframeData[stateKey] || {};
  const lfos = lfoData[stateKey] || {};
  return [...redrawParameters].some(parameter => (
    Array.isArray(keyframes[parameter]) && keyframes[parameter].length > 0
  ) || lfos[parameter]?.enabled === true);
}

export async function bakeStarCrawlTexturesForExport({
  tracks = [],
  keyframeData = {},
  lfoData = {},
  documentTarget = globalThis.document,
  ensureFont = (config) => ensureStarCrawlFont(
    config,
    documentTarget?.fonts,
  ),
  renderCanvas = (config) => renderStarCrawlTextureCanvas(
    config,
    { documentTarget },
  ),
} = {}) {
  const textures = [];
  const skipped = [];

  for (const track of tracks) {
    if (track?.type !== 'scene') continue;
    for (const [segmentIndex, segment] of (track.segments || []).entries()) {
      const config = segment?.sceneOverrides?.starCrawl;
      if (!config?.enabled || !segment?.id) continue;
      if (starCrawlTextureIsAnimated(
        track,
        segment,
        segmentIndex,
        keyframeData,
        lfoData,
      )) {
        skipped.push({
          segmentId: String(segment.id),
          reason: 'animated-typography',
        });
        continue;
      }

      const fontReady = await ensureFont(config);
      if (fontReady === false) {
        throw new Error(`Could not load the crawl font for ${segment.name || segment.id}`);
      }
      const canvas = renderCanvas(config);
      const pngDataUrl = canvas?.toDataURL?.('image/png');
      if (!pngDataUrl?.startsWith('data:image/png;base64,')) {
        throw new Error(`Could not bake crawl texture for ${segment.name || segment.id}`);
      }
      textures.push({
        segment_id: String(segment.id),
        png_data_url: pngDataUrl,
      });
    }
  }

  return { textures, skipped };
}
