/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

/**
 * Supports @importguide tag.
 * Allows to import contents of a guide into another guide.
 * Use case: when one guide is used in two places. To avoid duplicating guides.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	const allGuides = hexo.projectGlobals.common.allGuides;
	const importRegExp = /<p>{@importguide\s+([^}]+)}<\/p>/g;

	page.content = page.content.replace( importRegExp, ( match, pathToGuide ) => {
		const importedGuide = allGuides.find( g => {
			return g.path === pathToGuide;
		} );

		if ( !importedGuide ) {
			console.error( `Failed to import a guide from ${ pathToGuide } in document: ${ page.source }` );

			return match;
		}

		page.title = importedGuide.title;

		return importedGuide.content;
	} );
}, 30 );
