"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const fs_1 = require("fs");
const path_1 = require("path");
function moveDirectory(tree, from, to) {
    if (!tree.exists(from))
        return;
    const children = tree.children(from);
    for (const child of children) {
        const childPath = `${from}/${child}`;
        if (tree.isFile(childPath)) {
            const content = tree.read(childPath);
            if (content) {
                tree.write(`${to}/${child}`, content);
            }
            tree.delete(childPath);
        }
        else {
            moveDirectory(tree, childPath, `${to}/${child}`);
        }
    }
}
function generateDocusaurusConfig(experienceName, hasSubName, subNameKebab) {
    const humanReadable = (0, devkit_1.names)(experienceName).className.replace(/([a-z])([A-Z])/g, '$1 $2');
    const lowerDashCase = (0, devkit_1.names)(experienceName).fileName;
    const title = hasSubName
        ? `${humanReadable} | ${subNameKebab} Documentation`
        : `${humanReadable} Documentation`;
    const navbarTitle = hasSubName
        ? `${humanReadable} | ${subNameKebab}`
        : humanReadable;
    const baseUrl = hasSubName
        ? `/_/${lowerDashCase}/${subNameKebab}`
        : `/${lowerDashCase}`;
    return `import { themes as prismThemes } from 'prism-react-renderer';
import type { Config } from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
import typedocPlugins from './plugins/typedoc-plugins';

const config: Config = {
  title: '${title}',
  tagline: '',
  favicon: 'img/favicon.ico',

  url: 'https://docs.kaltura.com',
  baseUrl: '${baseUrl}',

  onBrokenLinks: 'warn',
  onBrokenMarkdownLinks: 'warn',

  noIndex: true,

  i18n: {
    defaultLocale: 'en',
    locales: ['en'],
  },

  presets: [
    [
      'classic',
      {
        docs: false,
        blog: false,
        theme: {
          customCss: './src/css/custom.css',
        },
        sitemap: {
          ignorePatterns: ['**'],
        },
      } satisfies Preset.Options,
    ],
  ],
  plugins: [
    [
      '@docusaurus/plugin-content-docs',
      {
        path: 'docs/documentations',
        routeBasePath: 'documentations',
        sidebarPath: './sidebars.ts',
      },
    ],
    [
      '@docusaurus/plugin-content-docs',
      {
        id: 'reference',
        path: 'docs/reference',
        routeBasePath: 'reference',
        sidebarPath: './sidebars.ts',
      },
    ],
    [
      '@docusaurus/plugin-content-docs',
      {
        id: 'changelog',
        path: 'docs/changelog',
        routeBasePath: 'changelog',
        sidebarPath: './sidebars.ts',
      },
    ],
    ...typedocPlugins,
  ],
  themes: [
    '@docusaurus/theme-mermaid',
    [
      '@easyops-cn/docusaurus-search-local',
      {
        hashed: true,
        indexBlog: false,
        forceIgnoreNoIndex: true,
        docsRouteBasePath: ['documentations', 'reference', 'changelog'],
      },
    ],
  ],
  markdown: {
    mermaid: true,
  },
  themeConfig: {
    colorMode: {
      defaultMode: 'light',
      disableSwitch: false,
      respectPrefersColorScheme: true,
    },
    image: 'img/social-card.png',
    navbar: {
      title: '${navbarTitle}',
      logo: {
        alt: 'Logo',
        src: 'img/logo.svg',
        srcDark: 'img/logo_dark.svg',
      },
      items: [
        {
          to: 'documentations/overview',
          label: 'Documentations',
          position: 'left',
        },
        {
          to: 'reference/overview',
          label: 'Reference',
          position: 'left',
        },
        {
          to: 'changelog/overview',
          label: 'Changelog',
          position: 'left',
        },
      ],
    },
    prism: {
      theme: prismThemes.github,
      darkTheme: prismThemes.dracula,
    },
  } satisfies Preset.ThemeConfig,
};

export default config;
`;
}
async function update(tree) {
    devkit_1.logger.info('🔄 Updating documentation sites to new multi-plugin structure...');
    const docsBasePath = 'unisphere/documentation';
    if (!tree.exists(docsBasePath)) {
        devkit_1.logger.info('ℹ️ No documentation sites found, skipping');
        return;
    }
    const docsSites = tree.children(docsBasePath);
    if (docsSites.length === 0) {
        devkit_1.logger.info('ℹ️ No documentation sites found, skipping');
        return;
    }
    // Read .unisphere config for experience name
    let experienceName = '';
    if (tree.exists('.unisphere')) {
        try {
            const config = (0, devkit_1.readJson)(tree, '.unisphere');
            experienceName = config.name || '';
        }
        catch {
            devkit_1.logger.warn('⚠️ Could not read .unisphere config');
        }
    }
    // Read migration template files
    const sidebarsContent = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, 'templates', 'sidebars.ts.template'), 'utf-8');
    const cssContent = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, 'templates', 'custom.css'), 'utf-8');
    const navbarContent = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, 'templates', 'navbar-content.tsx'), 'utf-8');
    const navbarStylesContent = (0, fs_1.readFileSync)((0, path_1.join)(__dirname, 'templates', 'navbar-content-styles.module.css'), 'utf-8');
    let updatedCount = 0;
    for (const site of docsSites) {
        const sitePath = `${docsBasePath}/${site}`;
        try {
            // Determine if this is a sub-documentation site
            const experienceNameLower = experienceName ? (0, devkit_1.names)(experienceName).fileName : '';
            const hasSubName = experienceNameLower !== '' && site !== experienceNameLower;
            const subNameKebab = hasSubName ? site.replace(`${experienceNameLower}-`, '') : '';
            // 1. Move docs/getting-started → docs/documentations
            const gettingStartedPath = `${sitePath}/docs/getting-started`;
            const documentationsPath = `${sitePath}/docs/documentations`;
            if (tree.exists(gettingStartedPath) && !tree.exists(documentationsPath)) {
                moveDirectory(tree, gettingStartedPath, documentationsPath);
                devkit_1.logger.info(`  ✅ Moved docs/getting-started → docs/documentations in ${site}`);
            }
            // 2. Move docs/api → docs/reference
            const apiPath = `${sitePath}/docs/api`;
            const referencePath = `${sitePath}/docs/reference`;
            if (tree.exists(apiPath) && !tree.exists(referencePath)) {
                moveDirectory(tree, apiPath, referencePath);
                devkit_1.logger.info(`  ✅ Moved docs/api → docs/reference in ${site}`);
            }
            // 3. Update docusaurus.config.ts
            const configPath = `${sitePath}/docusaurus.config.ts`;
            const nameToUse = experienceName || site;
            const configContent = generateDocusaurusConfig(nameToUse, hasSubName, subNameKebab);
            tree.write(configPath, configContent);
            devkit_1.logger.info(`  ✅ Updated docusaurus.config.ts in ${site}`);
            // 4. Update sidebars.ts
            tree.write(`${sitePath}/sidebars.ts`, sidebarsContent);
            devkit_1.logger.info(`  ✅ Updated sidebars.ts in ${site}`);
            // 5. Update src/css/custom.css
            tree.write(`${sitePath}/src/css/custom.css`, cssContent);
            devkit_1.logger.info(`  ✅ Updated src/css/custom.css in ${site}`);
            // 6. Update src/theme/Navbar/Content/index.tsx
            tree.write(`${sitePath}/src/theme/Navbar/Content/index.tsx`, navbarContent);
            devkit_1.logger.info(`  ✅ Updated Navbar Content in ${site}`);
            // 7. Update src/theme/Navbar/Content/styles.module.css
            tree.write(`${sitePath}/src/theme/Navbar/Content/styles.module.css`, navbarStylesContent);
            devkit_1.logger.info(`  ✅ Updated Navbar Content styles in ${site}`);
            updatedCount++;
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            devkit_1.logger.warn(`⚠️ Failed to update ${site}: ${errorMessage}`);
        }
    }
    devkit_1.logger.info(`✅ Updated ${updatedCount} documentation site(s) to new structure`);
    await (0, devkit_1.formatFiles)(tree);
}
