// Copyright 2025 Zentrum für Digitale Souveränität der Öffentlichen Verwaltung (ZenDiS) GmbH.
// SPDX-License-Identifier: MIT

import nextra from 'nextra'
import { visit } from 'unist-util-visit'
import fs from 'fs'
import path from 'path'
import yaml from 'js-yaml'

var transformer = function (ast) {
    const glossaryPath = path.join(process.cwd(), '/.glossary.yaml')
    var acronyms = {}

    try {
        const fileContents = fs.readFileSync(glossaryPath, 'utf8')
        acronyms = yaml.load(fileContents)
    } catch (error) {
        console.error('Error loading glossary:', error)
    }

    var acronymsRegExp = new RegExp(
        '\\b('.concat(Object.keys(acronyms).join('|'), ')\\b'),
        'g',
    )

    visit(ast, 'paragraph', function (node) {
        // Replace acronyms in text nodes
        node.children = node.children
            .map(function (child) {
                if (child.type === 'text') {
                    // check if the text node contains an acronym
                    // if so, we return multiple new abbrev and text nodes
                    const newChildren = child.value
                        .split(acronymsRegExp)
                        .map(function (part) {
                            if (acronyms[part]) {
                                return {
                                    type: 'abbr',
                                    data: {
                                        hName: 'abbr',
                                        hChildren: [
                                            {
                                                type: 'text',
                                                value: part,
                                            },
                                        ],
                                        hProperties: {
                                            title: acronyms[part],
                                        },
                                    },
                                }
                            } else {
                                return {
                                    type: 'text',
                                    value: part,
                                }
                            }
                        })
                    return newChildren
                }

                return [child]
            })
            .flat()
    })

    return ast
}

const remarkAbbrev = function () {
    return transformer
}

const nextConfig = {
    output: 'export',
    images: {
        unoptimized: true, // mandatory, otherwise won't export
    },
}
const withNextra = nextra({
    theme: 'nextra-theme-docs',
    themeConfig: './theme.config.tsx',
    mdxOptions: {
        remarkPlugins: [remarkAbbrev],
    },
})

export default withNextra(nextConfig)