import {
  assertResourceTenant
} from "./chunk-K7DLILHK.js";
import {
  routeWrap
} from "./chunk-QSHK4MUE.js";
import {
  getSessionRow
} from "./chunk-SEGKFEG5.js";
import {
  init_clock,
  nowMs,
  toIso
} from "./chunk-HFDLUBWN.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/debug-prompt.ts
init_clock();
function isDebugPromptRequested(request) {
  const header = request.headers.get("x-agentstep-debug");
  if (header && header.trim().toLowerCase() === "prompt") return true;
  try {
    const url = new URL(request.url);
    const q = url.searchParams.get("debug");
    if (q && q.toLowerCase() === "prompt") return true;
  } catch {
  }
  return false;
}
var SECRET_KEY_RE = /(_KEY|_TOKEN|_SECRET|_PASSWORD)$/i;
var KNOWN_SECRET_KEYS = /* @__PURE__ */ new Set([
  "ANTHROPIC_API_KEY",
  "OPENAI_API_KEY",
  "GEMINI_API_KEY",
  "CODEX_API_KEY",
  "CLAUDE_CODE_OAUTH_TOKEN",
  "GOOGLE_API_KEY",
  "AGENTSTEP_LICENSE_KEY",
  // Opencode bakes its config (which may contain provider keys) into
  // this env var as a JSON blob. Redact wholesale rather than try to
  // parse + scrub.
  "OPENCODE_CONFIG_CONTENT"
]);
function redactEnv(env) {
  const out = {};
  for (const [k, v] of Object.entries(env)) {
    if (KNOWN_SECRET_KEYS.has(k) || SECRET_KEY_RE.test(k)) {
      out[k] = `<redacted:len=${v.length}>`;
    } else {
      out[k] = v;
    }
  }
  return out;
}
var RETENTION_MS = 60 * 60 * 1e3;
function handleGetDebugPrompt(request, id) {
  return routeWrap(request, async ({ auth }) => {
    if (!id) throw badRequest("session id required");
    const row = getSessionRow(id);
    if (!row) throw notFound(`session not found: ${id}`);
    assertResourceTenant(auth, row.tenant_id, `session not found: ${id}`);
    if (row.debug_prompt_json === null) {
      throw notFound("debug-prompt capture was not enabled for this session");
    }
    if (row.debug_prompt_json === '{"pending":true}') {
      throw notFound("debug-prompt capture pending \u2014 no turn has run yet");
    }
    let payload;
    try {
      payload = JSON.parse(row.debug_prompt_json);
    } catch {
      throw notFound("debug-prompt payload is corrupt");
    }
    const capturedAtMs = Date.parse(payload.captured_at);
    if (Number.isFinite(capturedAtMs) && nowMs() - capturedAtMs > RETENTION_MS) {
      return Response.json(
        {
          type: "error",
          error: {
            type: "invalid_request_error",
            message: `debug-prompt expired (captured ${toIso(capturedAtMs)}, retention 1h)`
          }
        },
        { status: 410 }
      );
    }
    return Response.json(payload, { status: 200 });
  });
}

export {
  isDebugPromptRequested,
  redactEnv,
  handleGetDebugPrompt
};
