// The metadata header the launcher reads from the compiled bundle: name / icon / preload / gl / 2d /
// ar. Single source of truth — the backend and CLI both call this (today they mirror it by hand).
//
// Detection keys on the *bundled* `_creator*` calls, which the SDK's thin wrappers still emit
// (new Scene() → _creator.createScene, new Scene2D() → _creator2d.createScene), so the re-skin keeps
// the exact same signals the old worker bundles produced.

export type HeaderOptions = {
  /** Generated-icon URL (backend supplies it; the CLI omits it). */
  icon?: string
}

export const buildHeader = (name: string, code: string, opts: HeaderOptions = {}): string => {
  let header = `// name: ${name.slice(0, 20)}\n`
  if (opts.icon) header += `// icon: ${opts.icon}\n`
  header += `// last-updated: ${new Date().toISOString()}\n`

  // Local assets to preload: explicit fetchLocal() calls + implicit engine archives.
  const localAssets = new Set<string>()
  for (const m of code.matchAll(/_creatorUtils\.fetchLocal\((.+?)\)/g)) {
    localAssets.add(m[1].replaceAll(/['"]/g, "").trim())
  }
  if (/_creator\.createGlb/.test(code)) localAssets.add("uberarchive")
  if (/_creator\.captureImage/.test(code)) localAssets.add("capture")
  if (localAssets.size > 0) header += `// preload: ${[ ...localAssets ].join(";")}\n`

  // GL: disabled unless the project touches the 3D engine; deferred if it lazily creates the engine.
  if (!code.includes("_creator.createScene") && !code.includes("_creator.createEntity")) header += `// gl: disable\n`
  else if (code.includes("_creator.createEngine")) header += `// gl: defer\n`

  // 2D (creator-2d) — non-exclusive: emitted alongside `gl: disable` so hosts skip Filament and a
  // 2D-aware host brings up the lightweight sokol engine instead.
  if (code.includes("_creator2d.")) header += `// 2d: enable\n`

  if (code.includes("_creator.createARController")) header += "// ar: enable"
  header += "\n"
  return header
}

/** Same engine signals the header uses, for callers that need the project kind (e.g. icon type). */
export const detectProjectKind = (code: string): "ar" | "ui" | "2d" | "3d" => {
  if (code.includes("_creator.createARController")) return "ar"
  if (code.includes("_creator2d.")) return "2d"
  if (!code.includes("_creator.")) return "ui"
  return "3d"
}
