const HTML_CSP = [
  "default-src 'none'",
  "img-src 'self' data:",
  "style-src 'self' 'unsafe-inline'",
  "script-src 'none'",
  "font-src 'self' data:",
  "connect-src 'none'",
  "media-src 'none'",
  "frame-src 'none'",
  "object-src 'none'",
  "base-uri 'none'",
  "form-action 'none'",
  "sandbox"
].join("; ");
const SVG_CSP = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; object-src 'none'; base-uri 'none'; form-action 'none'; sandbox";

export async function resolveArtifactRoute(req, url, context) {
  const match = url.pathname.match(/^\/sessions\/([^/]+)\/artifacts\/([^/]+)(?:\/(.+))?$/);
  if (req.method !== "GET" || !match) return null;
  const session = context.getSession(match[1]);
  const artifact = await context.getArtifact(session, match[2], match[3]);
  return { status: 200, artifact };
}

export function artifactHeaders(artifact) {
  const mimeType = artifact.mimeType || "application/octet-stream";
  const name = safeHeaderFilename(artifact.name);
  const inline = mimeType === "text/html"
    || mimeType === "application/pdf"
    || mimeType.startsWith("image/")
    || mimeType.startsWith("text/")
    || mimeType === "application/json";
  return {
    "content-type": contentType(mimeType),
    "content-length": String(artifact.size ?? artifact.data?.length ?? 0),
    "content-disposition": `${inline ? "inline" : "attachment"}; filename="${name}"`,
    "cache-control": "private, no-store",
    "x-content-type-options": "nosniff",
    ...(mimeType === "text/html" ? { "content-security-policy": HTML_CSP } : {}),
    ...(mimeType === "image/svg+xml" ? { "content-security-policy": SVG_CSP } : {})
  };
}

function contentType(mimeType) {
  return mimeType.startsWith("text/") || mimeType === "application/json"
    ? `${mimeType}; charset=utf-8`
    : mimeType;
}

function safeHeaderFilename(value) {
  return String(value ?? "artifact").replace(/[\r\n"\\/]/g, "_") || "artifact";
}
