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

'use strict';

/**
 * Support @var tag.
 * When placed in a guide, this filter replaces it with a variable available in project's umberto.json config
 * or in hexo.projectGlobals data.
 * Example: {@var version} is replaced with umberto.json version property.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	page.content = page.content.replace( /{@var[^}]*}/g, match => {
		const innerMatch = /@var\s+(\w+)-(\w+)/.exec( match );

		if ( !innerMatch ) {
			return onError( match, page.source );
		}

		const project = innerMatch[ 1 ];
		const variable = innerMatch[ 2 ];

		if ( !hexo.projectGlobals || !hexo.projectGlobals[ project ] ) {
			return onError( match, page.source );
		}

		const value = getValue( project, variable );

		if ( value === null ) {
			return onError( match, page.source );
		}

		return value;
	} );
} );

/**
 * @param {String} project
 * @param {String} variable
 * @return {*|null}
 */
function getValue( project, variable ) {
	const projectGlobals = hexo.projectGlobals[ project ];

	if ( projectGlobals.config[ variable ] ) {
		return projectGlobals.config[ variable ];
	}

	if ( projectGlobals[ variable ] ) {
		return projectGlobals[ variable ];
	}

	return null;
}

function onError( match, source ) {
	console.error( `Failed to read variable ${ match } in ${ source }` );
	process.exitCode = 1;

	return match;
}

