---
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 { LATEST_VERSION } from "../../config/versions";

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

export async function getStaticPaths() {
  const KNOWN_LOCALES = ["en", "pt-br"];
  const allDocs = await getCollection("docs");

  return [
    ...KNOWN_LOCALES.map((locale) => ({
      params: { locale },
      props: { doc: null },
    })),
    // Legacy path redirects (keep old URLs working without keeping old docs in the sidebar)
    ...KNOWN_LOCALES.flatMap((locale) => [
      {
        params: { locale, slug: "getting-started/context-engineers" },
        props: { doc: null },
      },
    ]),
    // Legacy redirect paths: generate /en/... and /pt-br/... for all latest docs
    // so old production URLs get redirected to /latest/en/... equivalents
    ...allDocs
      .filter((doc) => doc.id.split("/")[0] === LATEST_VERSION.id)
      .map((doc) => {
        const parts = doc.id.split("/");
        const locale = parts[1];
        const slug = parts.slice(2).join("/");

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

const { doc } = Astro.props;
const slug = Astro.params.slug;

// Legacy redirects
if (slug === "getting-started/context-engineers") {
  return Astro.redirect(`/${lang}/getting-started/developers`);
}

// Redirect to introduction if no document is found (i.e., when visiting /en or /pt-br)
// If a slug is present, preserve it so legacy /en/... URLs redirect to /latest/en/...
if (!doc) {
  if (slug) {
    return Astro.redirect(`/${LATEST_VERSION.id}/${lang}/${slug}`);
  }
  return Astro.redirect(`/${LATEST_VERSION.id}/${lang}/studio/quickstart`);
}
---

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