---
import { useTranslations } from "../../../i18n/utils";
import { ui, languages } from "../../../i18n/ui";
import DocsLayout from "../../../layouts/DocsLayout.astro";
import { getCollection } from "astro:content";
import RenderDocument from "../../../components/ui/RenderDocument.astro";

import {
  VERSION_IDS,
  LATEST_VERSION,
  versions,
} from "../../../config/versions";

const version = Astro.params.version;
const lang = Astro.params.locale;
const t = useTranslations(lang as keyof typeof ui);

export async function getStaticPaths() {
  const allDocs = await getCollection("docs");

  return [
    // "latest" alias paths — redirect to actual version
    ...Object.keys(languages).map((locale) => ({
      params: { version: "latest", locale },
      props: { doc: null, version: "latest" },
    })),
    // "latest" alias for all docs across all versions (so old /latest/en/... URLs redirect properly)
    ...allDocs
      .flatMap((doc) => {
        const parts = doc.id.split("/");
        const locale = parts[1];
        const slug = parts.slice(2).join("/");
        // Check if this slug exists in the latest version
        const existsInLatest = allDocs.some(
          (d) => d.id === `${LATEST_VERSION.id}/${locale}/${slug}`,
        );
        return {
          params: { version: "latest", locale, slug },
          props: { doc: null, version: "latest", existsInLatest },
        };
      })
      // Deduplicate by locale+slug (same slug may exist in multiple versions)
      .filter(
        (entry, index, arr) =>
          arr.findIndex(
            (e) =>
              e.params.locale === entry.params.locale &&
              e.params.slug === entry.params.slug,
          ) === index,
      ),

    // Old "mcp-mesh" slugs (renamed to "studio") — keep legacy URLs redirecting
    ...allDocs
      .filter(
        (doc) =>
          doc.id.startsWith("deco-chat/") && doc.id.split("/")[2] === "studio",
      )
      .map((doc) => {
        const parts = doc.id.split("/");
        return {
          params: {
            version: "deco-chat",
            locale: parts[1],
            slug: ["mcp-mesh", ...parts.slice(3)].join("/"),
          },
          props: { doc: null, version: "deco-chat" },
        };
      }),

    // Actual versioned paths
    ...VERSION_IDS.flatMap((version) => [
      // Root version paths
      ...Object.keys(languages).map((locale) => ({
        params: { version, locale },
        props: { doc: null, version },
      })),
      // Legacy path redirects
      ...Object.keys(languages).flatMap((locale) => [
        {
          params: {
            version,
            locale,
            slug: "getting-started/context-engineers",
          },
          props: { doc: null, version },
        },
      ]),
      // All docs filtered by version
      ...allDocs
        .filter((doc) => doc.id.startsWith(`${version}/`))
        .map((doc) => {
          const parts = doc.id.split("/");
          const locale = parts[1];
          const slug = parts.slice(2).join("/");

          return {
            params: { version, locale, slug },
            props: { doc, version },
          };
        }),
    ]),
  ];
}

const { doc, version: propVersion, existsInLatest } = Astro.props;
const slug = Astro.params.slug;

// Redirect "latest" alias to actual version
if (version === "latest") {
  if (slug && existsInLatest) {
    return Astro.redirect(`/${LATEST_VERSION.id}/${lang}/${slug}`);
  }
  return Astro.redirect(`/${LATEST_VERSION.id}/${lang}/${LATEST_VERSION.root}`);
}

// Legacy redirects
if (slug?.startsWith("mcp-mesh/")) {
  return Astro.redirect(
    `/${version}/${lang}/${slug.replace(/^mcp-mesh\//, "studio/")}`,
  );
}
if (slug === "getting-started/context-engineers") {
  return Astro.redirect(`/${version}/${lang}/getting-started/developers`);
}

// Redirect to version root if no document is found
if (!doc) {
  const versionConfig = versions.find((v) => v.id === version);
  const root = versionConfig?.root ?? "studio/quickstart";
  return Astro.redirect(`/${version}/${lang}/${root}`);
}
---

<DocsLayout title={doc.data.title} doc={doc} version={propVersion}>
  <RenderDocument doc={doc} />
</DocsLayout>
