// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: MIT

import { defineConfig } from "astro/config";
import starlight from "@astrojs/starlight";
import sitemap from "@astrojs/sitemap";
import { slintStarlightFaviconHead } from "@slint/common-files/src/utils/starlight-favicon-head";
import {
    SLINT_STARLIGHT_TRAILING_SLASH,
    slintStarlightLinksValidatorPlugin,
    slintStarlightMarkdownRehypeExternalLinksOnly,
} from "@slint/common-files/src/utils/starlight-site-defaults";
import { slintStarlightSocial } from "@slint/common-files/src/utils/starlight-social";
import {
    CPP_DOCS_BASE_PATH,
    CPP_DOCS_BASE_URL,
    cppDocsPublicAsset,
} from "./src/cpp-site-config.mjs";

// The API-reference sidebar is generated by `pnpm gen:api` (organized by
// namespace). Before that has run — e.g. building only the prose pages — fall
// back to an empty group so the config still loads.
let _cppApiSidebar = [];
try {
    _cppApiSidebar = (await import("./src/api-sidebar.generated.mjs")).default;
} catch {
    // Not generated yet; the API Reference group renders empty.
}

const _cppOrigin = String(CPP_DOCS_BASE_URL).replace(/\/+$/, "");
const _cppAtRoot = CPP_DOCS_BASE_PATH === "/";
/** Canonical URL and optional `base` (same pattern as `docs/nodejs/astro.config.mjs`). */
const _cppSite = _cppAtRoot
    ? _cppOrigin
    : `${_cppOrigin}${CPP_DOCS_BASE_PATH.replace(/\/*$/, "/")}`;
const _cppBase = _cppAtRoot
    ? undefined
    : CPP_DOCS_BASE_PATH.replace(/\/*$/, "/");

export default defineConfig({
    site: _cppSite,
    ...(_cppBase ? { base: _cppBase } : {}),
    trailingSlash: SLINT_STARLIGHT_TRAILING_SLASH,
    markdown: slintStarlightMarkdownRehypeExternalLinksOnly(),
    vite: {
        resolve: {
            // Swap our PagefindUI wrapper (which adds `processTerm`) in for
            // `@pagefind/default-ui`, so qualified C++ identifier searches
            // resolve. Exact-match `find` so subpath imports (the CSS, the
            // wrapper's own import) are left alone.
            alias: [
                {
                    find: /^@pagefind\/default-ui$/,
                    replacement: new URL(
                        "./src/pagefind-ui-override.mjs",
                        import.meta.url,
                    ).pathname,
                },
            ],
        },
    },
    integrations: [
        sitemap(),
        starlight({
            title: "Slint C++ API",
            logo: {
                src: "./src/assets/slint-logo-small-light.svg",
            },
            customCss: [
                "@slint/common-files/src/styles/starlight-slint-custom.css",
                "@slint/common-files/src/styles/starlight-slint-theme.css",
                "./src/styles/api-signature.css",
            ],
            favicon: "favicon.svg",
            components: {
                Footer: "@slint/common-files/src/components/Footer.astro",
                Header: "@slint/common-files/src/components/HeaderCppDocs.astro",
                Banner: "@slint/common-files/src/components/Banner.astro",
            },
            plugins: [
                // Internal links are relative so they resolve under the deploy
                // base path (e.g. /master/docs/cpp/); root-absolute links would
                // not be rewritten with the base by Astro.
                slintStarlightLinksValidatorPlugin({
                    errorOnRelativeLinks: false,
                }),
                // No starlight-expand-all-sidebar-groups here: the prose groups
                // are top-level and expand by default, while the API Reference's
                // per-namespace sub-groups set `collapsed: true` so they start
                // collapsed instead of being force-expanded.
            ],
            social: slintStarlightSocial,
            head: slintStarlightFaviconHead(cppDocsPublicAsset),
            // The "API Reference" group is generated by `pnpm gen:api` (see
            // `scripts/generate-api.ts`) into `./src/api-sidebar.generated.mjs`
            // and imported above. It is empty until that has run, so the prose
            // pages still build before the API reference has been generated.
            sidebar: [
                { label: "Overview", slug: "index" },
                {
                    label: "Getting Started",
                    items: [
                        {
                            label: "Set Up Development Environment",
                            slug: "cmake",
                        },
                        { label: "Getting Started", slug: "getting-started" },
                        { label: "Live Preview", slug: "live-preview" },
                    ],
                },
                {
                    label: "C++ / .slint Integration",
                    items: [
                        { label: "Overview", slug: "overview" },
                        { label: "Type Mappings", slug: "types" },
                        { label: "Generated Code", slug: "generated-code" },
                    ],
                },
                {
                    label: "Microcontrollers",
                    items: [
                        { label: "Introduction", slug: "mcu/intro" },
                        { label: "ESP-IDF", slug: "mcu/esp-idf" },
                        {
                            label: "ESP-IDF Troubleshooting",
                            slug: "mcu/esp-idf/troubleshoot",
                        },
                        { label: "STM32", slug: "mcu/stm32" },
                        { label: "STM32 Generic", slug: "mcu/stm32/generic" },
                        { label: "Generic MCU", slug: "mcu/generic" },
                    ],
                },
                {
                    label: "CMake Reference",
                    collapsed: true,
                    items: [
                        { label: "Overview", slug: "cmake-reference" },
                        {
                            label: "slint_target_sources",
                            slug: "cmake-reference/slint-target-sources",
                        },
                        {
                            label: "Resource Embedding",
                            slug: "cmake-reference/resource-embedding",
                        },
                        {
                            label: "Scale Factor for Microcontrollers",
                            slug: "cmake-reference/scale-factor",
                        },
                        {
                            label: "Bundle Translations",
                            slug: "cmake-reference/bundle-translations",
                        },
                        {
                            label: "Translation Domain",
                            slug: "cmake-reference/translation-domain",
                        },
                        {
                            label: "Disable Default Translation Context",
                            slug: "cmake-reference/disable-default-translation-context",
                        },
                    ],
                },
                {
                    label: "API Reference",
                    // Organized by namespace; each group lists the namespace's
                    // types and links to its free functions/enums. Generated by
                    // `pnpm gen:api` into ./src/api-sidebar.generated.mjs.
                    items: _cppApiSidebar,
                },
                { autogenerate: { directory: "generated" } },
            ],
        }),
    ],
});
