// @bun
import {
  getEmbeddedAssets
} from "./chunk-h857yazx.js";
import {
  AgentProjectGenerator
} from "./chunk-7krp2mgz.js";

// src/utils/ensure-templates.ts
import { createHash } from "crypto";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { join, dirname } from "path";
async function extractEmbeddedTemplates() {
  const templateAssets = getEmbeddedAssets().filter((a) => a.path.startsWith("/templates/"));
  if (templateAssets.length === 0) {
    return null;
  }
  const hasher = createHash("md5");
  for (const asset of templateAssets) {
    hasher.update(asset.path);
    hasher.update(new Uint8Array(await Bun.file(asset.file).arrayBuffer()));
  }
  const versionHash = hasher.digest("hex").slice(0, 12);
  const tmpDir = join(process.env.TMPDIR || "/tmp", `adk-templates-${versionHash}`);
  for (const asset of templateAssets) {
    const filePath = join(tmpDir, asset.path.replace(/^\/templates\//, ""));
    if (existsSync(filePath)) {
      continue;
    }
    const dir = dirname(filePath);
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true });
    }
    const content = await Bun.file(asset.file).arrayBuffer();
    writeFileSync(filePath, Buffer.from(content));
  }
  return tmpDir;
}
async function ensureTemplatesAvailable() {
  const extracted = await extractEmbeddedTemplates();
  if (extracted) {
    AgentProjectGenerator.setTemplatesRoot(extracted);
    return;
  }
  AgentProjectGenerator.getAvailableTemplates();
}

export { ensureTemplatesAvailable };
