const { join, resolve } = require('node:path');

const { config } = require('@apify/docs-theme');

const { externalLinkProcessor } = require('./tools/utils/externalLink');
const versions = require('./versions.json');

const GROUP_ORDER = [
    'Actor',
    'Charging',
    'Configuration',
    'Event data',
    'Event managers',
    'Events',
    'Request loaders',
    'Storage clients',
    'Storage data',
    'Storages',
];

const groupSort = (g1, g2) => {
    const i1 = GROUP_ORDER.indexOf(g1);
    const i2 = GROUP_ORDER.indexOf(g2);
    // Both known – sort by defined order
    if (i1 !== -1 && i2 !== -1) return i1 - i2;
    // Unknown groups go after known ones
    if (i1 !== -1) return -1;
    if (i2 !== -1) return 1;
    // Both unknown – alphabetical
    return g1.localeCompare(g2);
};

const { absoluteUrl } = config;

/** @type {Partial<import('@docusaurus/types').DocusaurusConfig>} */
module.exports = {
    title: 'SDK for Python | Apify Documentation',
    url: absoluteUrl,
    baseUrl: '/sdk/python',
    trailingSlash: false,
    organizationName: 'apify',
    projectName: 'apify-sdk-python',
    favicon: 'img/favicon.ico',
    scripts: ['/js/custom.js', ...(config.scripts ?? [])],
    githubHost: 'github.com',
    future: {
        experimental_faster: {
            // ssgWorkerThreads: true,
            swcJsLoader: true,
            swcJsMinimizer: true,
            swcHtmlMinimizer: true,
            lightningCssMinimizer: true,
            rspackBundler: true,
            mdxCrossCompilerCache: true,
            rspackPersistentCache: true,
        },
        v4: {
            removeLegacyPostBuildHeadAttribute: true,
            useCssCascadeLayers: false, // this breaks styles on homepage and link colors everywhere
        },
    },
    onBrokenLinks:
    /** @type {import('@docusaurus/types').ReportingSeverity} */ ('warn'),
    onBrokenMarkdownLinks:
    /** @type {import('@docusaurus/types').ReportingSeverity} */ ('warn'),
    themes: [
        [
            '@apify/docs-theme',
            {
                changelogFromRoot: true,
                subNavbar: {
                    title: 'SDK for Python',
                    items: [
                        {
                            type: 'doc',
                            docId: 'introduction/introduction',
                            label: 'Docs',
                            position: 'left',
                            activeBaseRegex: '/docs(?!/changelog)',
                        },
                        {
                            type: 'custom-versioned-reference',
                            label: 'Reference',
                            position: 'left',
                            activeBaseRegex: '/reference',
                        },
                        {
                            type: 'doc',
                            docId: 'changelog',
                            label: 'Changelog',
                            position: 'left',
                            activeBaseRegex: '/docs/changelog',
                        },
                        {
                            href: 'https://github.com/apify/apify-sdk-python',
                            label: 'GitHub',
                            position: 'left',
                        },
                        {
                            type: 'docsVersionDropdown',
                            position: 'left',
                            className: 'navbar__item',
                            'data-api-links': JSON.stringify([
                                'reference/next',
                                ...versions.map((version, i) => (i === 0 ? 'reference' : `reference/${version}`)),
                            ]),
                            dropdownItemsBefore: [],
                            dropdownItemsAfter: [],
                        },
                    ],
                },
            },
        ],
    ],
    presets: /** @type {import('@docusaurus/types').PresetConfig[]} */ ([
        [
            '@docusaurus/preset-classic',
            /** @type {import('@docusaurus/preset-classic').Options} */
            ({
                docs: {
                    path: '../docs',
                    sidebarPath: './sidebars.js',
                    rehypePlugins: [externalLinkProcessor],
                    editUrl: 'https://github.com/apify/apify-sdk-python/edit/master/website/',
                },
                theme: {
                    customCss: require.resolve('./src/css/custom.css'),
                },
            }),
        ],
    ]),
    plugins: [
        [
            '@apify/docusaurus-plugin-typedoc-api',
            {
                projectRoot: '.',
                changelogs: false,
                readmes: false,
                packages: [{ path: '.' }],
                typedocOptions: {
                    excludeExternals: false,
                },
                sortSidebar: groupSort,
                routeBasePath: 'reference',
                python: true,
                pythonOptions: {
                    pythonModulePath: join(__dirname, '../src/apify'),
                    moduleShortcutsPath: join(__dirname, '/module_shortcuts.json'),
                },
                reexports: [
                    // Storages
                    {
                        url: 'https://crawlee.dev/python/api/class/Storage',
                        group: 'Storages',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/Dataset',
                        group: 'Storages',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/KeyValueStore',
                        group: 'Storages',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/RequestQueue',
                        group: 'Storages',
                    },
                    // Storage data
                    {
                        url: 'https://crawlee.dev/python/api/class/AddRequestsResponse',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/DatasetItemsListPage',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/DatasetMetadata',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/KeyValueStoreMetadata',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/KeyValueStoreRecord',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/KeyValueStoreRecordMetadata',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/ProcessedRequest',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/Request',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/RequestQueueMetadata',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/StorageMetadata',
                        group: 'Storage data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/ReqUnprocessedRequestuest',
                        group: 'Storage data',
                    },
                    // Event managers
                    {
                        url: 'https://crawlee.dev/python/api/class/EventManager',
                        group: 'Event managers',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/LocalEventManager',
                        group: 'Event managers',
                    },
                    // Events
                    {
                        url: 'https://crawlee.dev/python/api/enum/Event',
                        group: 'Events',
                    },
                    // Event data
                    {
                        url: 'https://crawlee.dev/python/api/class/EventAbortingData',
                        group: 'Event data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/EventExitData',
                        group: 'Event data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/EventMigratingData',
                        group: 'Event data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/EventPersistStateData',
                        group: 'Event data',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/EventSystemInfoData',
                        group: 'Event data',
                    },
                    // Storage clients
                    {
                        url: 'https://crawlee.dev/python/api/class/StorageClient',
                        group: 'Storage clients',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/MemoryStorageClient',
                        group: 'Storage clients',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/FileSystemStorageClient',
                        group: 'Storage clients',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/SqlStorageClient',
                        group: 'Storage clients',
                    },
                    // Request loaders
                    {
                        url: 'https://crawlee.dev/python/api/class/RequestLoader',
                        group: 'Request loaders',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/RequestManager',
                        group: 'Request loaders',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/RequestManagerTandem',
                        group: 'Request loaders',
                    },
                    {
                        url: 'https://crawlee.dev/python/api/class/SitemapRequestLoader',
                        group: 'Request loaders',
                    },
                ],
            },
        ],
        [
            resolve(__dirname, 'src/plugins/docusaurus-plugin-segment'),
            {
                writeKey: process.env.SEGMENT_TOKEN,
                allowedInDev: false,
            },
        ],
        [
            '@signalwire/docusaurus-plugin-llms-txt',
            {
                content: {
                    includeVersionedDocs: false,
                    enableLlmsFullTxt: true,
                    includeBlog: true,
                    includeGeneratedIndex: false,
                    includePages: true,
                    relativePaths: false,
                    excludeRoutes: [
                        '/sdk/python/reference/[0-9]*/**',
                        '/sdk/python/reference/[0-9]*',
                        '/sdk/python/reference/next/**',
                        '/sdk/python/reference/next',
                    ],
                },
            },
        ],
        ...config.plugins,
    ],
    themeConfig: {
        ...config.themeConfig,
        versions,
        tableOfContents: {
            ...config.themeConfig.tableOfContents,
            maxHeadingLevel: 5,
        },
        footer: {
            ...config.themeConfig.footer,
            logo: {
                ...config.themeConfig.footer.logo,
                href: 'docs/overview',
            },
        },
        image: 'https://docs.apify.com/sdk/python/img/docs-og.png',
    },
    staticDirectories: ['node_modules/@apify/docs-theme/static', 'static'],
    customFields: {
        ...(config.customFields ?? []),
    },
};
