const MARKDOWN_PATHS = new Map([
  ["/", "/index.md"],
  ["/en/", "/en/index.md"],
  ["/metoda/", "/metoda/index.md"],
  ["/en/method/", "/en/method/index.md"],
  ["/surse/", "/surse/index.md"],
  ["/en/sources/", "/en/sources/index.md"],
]);

const CONTENT_SIGNAL = "ai-train=no, search=yes, ai-input=yes";

function normalizedPath(pathname) {
  if (MARKDOWN_PATHS.has(pathname)) return pathname;
  if (pathname !== "/" && MARKDOWN_PATHS.has(`${pathname}/`)) return `${pathname}/`;
  return pathname;
}

function acceptsMarkdown(request) {
  const accept = request.headers.get("Accept") || "";
  const markdown = accept.match(/text\/markdown(?:\s*;\s*q=([0-9.]+))?/i);
  return Boolean(markdown && Number(markdown[1] ?? 1) > 0);
}

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const pagePath = normalizedPath(url.pathname);
    const markdownPath = MARKDOWN_PATHS.get(pagePath);
    let response;

    if (markdownPath && acceptsMarkdown(request)) {
      const markdownUrl = new URL(markdownPath, url);
      response = await env.ASSETS.fetch(new Request(markdownUrl, request));
    } else {
      response = await env.ASSETS.fetch(request);
    }

    const headers = new Headers(response.headers);
    if (url.pathname === "/downloads/DEXONLINE-NOTICE.md") {
      headers.set("Content-Type", "text/markdown; charset=utf-8");
    }
    headers.set("Content-Signal", CONTENT_SIGNAL);
    headers.set("X-Content-Type-Options", "nosniff");
    headers.set("Referrer-Policy", "strict-origin-when-cross-origin");

    if (markdownPath) {
      headers.set("Vary", "Accept");
      headers.set(
        "Link",
        `<${new URL(markdownPath, url.origin).href}>; rel="alternate"; type="text/markdown"`,
      );
      if (acceptsMarkdown(request)) {
        headers.set("Content-Type", "text/markdown; charset=utf-8");
      }
    }

    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers,
    });
  },
};
