import {
  readFile
} from "./chunk-STPT3SWU.js";
import {
  routeWrap
} from "./chunk-QSHK4MUE.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/google-compat/files.ts
init_client();
function buildTarArchive(files) {
  const blocks = [];
  for (const file of files) {
    const header = Buffer.alloc(512, 0);
    const name = file.name.slice(0, 100);
    header.write(name, 0, Math.min(name.length, 100), "utf8");
    header.write("0000644\0", 100, 8, "utf8");
    header.write("0000000\0", 108, 8, "utf8");
    header.write("0000000\0", 116, 8, "utf8");
    header.write(file.data.length.toString(8).padStart(11, "0") + "\0", 124, 12, "utf8");
    const mtime = Math.floor(Date.now() / 1e3);
    header.write(mtime.toString(8).padStart(11, "0") + "\0", 136, 12, "utf8");
    header.write("        ", 148, 8, "utf8");
    header.write("0", 156, 1, "utf8");
    header.write("ustar\0", 257, 6, "utf8");
    header.write("00", 263, 2, "utf8");
    let checksum = 0;
    for (let i = 0; i < 512; i++) {
      checksum += header[i];
    }
    header.write(checksum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "utf8");
    blocks.push(header);
    blocks.push(file.data);
    const remainder = file.data.length % 512;
    if (remainder > 0) {
      blocks.push(Buffer.alloc(512 - remainder, 0));
    }
  }
  blocks.push(Buffer.alloc(1024, 0));
  return Buffer.concat(blocks);
}
function handleGetEnvironmentFiles(request, fileRef) {
  return routeWrap(request, async () => {
    const match = fileRef.match(/^environment-(.+):download$/);
    if (!match) {
      throw badRequest("Invalid file reference format. Expected: environment-<envId>:download");
    }
    const envId = match[1];
    const db = getDb();
    const env = db.prepare(`SELECT id FROM environments WHERE id = ?`).get(envId);
    if (!env) {
      throw notFound(`environment not found: ${envId}`);
    }
    const sessions = db.prepare(
      `SELECT id FROM sessions WHERE environment_id = ?`
    ).all(envId);
    if (sessions.length === 0) {
      const emptyTar = Buffer.alloc(1024, 0);
      return new Response(emptyTar, {
        headers: {
          "Content-Type": "application/x-tar",
          "Content-Length": String(emptyTar.length)
        }
      });
    }
    const sessionIds = sessions.map((s) => s.id);
    const placeholders = sessionIds.map(() => "?").join(",");
    const fileRows = db.prepare(
      `SELECT * FROM files WHERE scope_type = 'session' AND scope_id IN (${placeholders})`
    ).all(...sessionIds);
    const tarFiles = [];
    for (const row of fileRows) {
      if (row.storage_path.startsWith("remote:")) continue;
      try {
        const data = readFile(row.storage_path);
        tarFiles.push({ name: row.filename, data });
      } catch {
      }
    }
    const tar = buildTarArchive(tarFiles);
    return new Response(tar, {
      headers: {
        "Content-Type": "application/x-tar",
        "Content-Length": String(tar.length)
      }
    });
  });
}

export {
  handleGetEnvironmentFiles
};
