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

'use strict';

const CHANGELOG_REGEXP = /\\?{@changelog ([^}]+)\\?}/g;
const VERSION_REGEXP = /^\d+\.\d+\.\d+$/;

/**
 * Replaces the `{@changelog X.Y.Z}` expression with the changelog entries for the specified version.
 * The version must follow the semantic versioning specification.
 *
 * The changelog callback must be specified in the project's configuration as the `projectConfig.insertChangelog` function.
 * See the `src/tasks/get-project-config.js` module.
 *
 * @param {Object} page
 * @param {Object} hexo
 * @returns {Object}
 */
module.exports = function insertChangelog( page, hexo ) {
	page.content = page.content.replace( CHANGELOG_REGEXP, ( match, version ) => {
		const projectConfig = hexo.projectGlobals[ page.projectName ].config;
		const projectChangelogCallback = projectConfig.insertChangelog;

		if ( !projectChangelogCallback ) {
			console.error( 'Could not find the `scripts[ "insert-changelog" ]` function in the project configuration.' );

			return match;
		}

		if ( match.startsWith( '\\{' ) ) {
			return match.replace( /^\\{/, '{' ).replace( /\\}$/, '}' );
		}

		const versionMatch = version.match( VERSION_REGEXP );

		if ( !versionMatch || versionMatch[ 0 ] !== version ) {
			console.error( 'The version must follow the semantic versioning specification.' );

			return match;
		}

		const changelog = projectChangelogCallback( version );

		if ( !changelog ) {
			console.error( `The "insertChangelog" callback did not return any value for the "${ version }" version.` );

			return match;
		}

		return changelog;
	} );

	return page;
};
