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

'use strict';

const upath = require( 'upath' );
const { globSync } = require( 'glob' );
const fs = require( 'fs-extra' );

/**
 * Replaces dst files with src files. Used to replace API guides with their cached versions.
 * Only for local dev builds.
 *
 * @param src
 * @param dst
 */
module.exports = ( src, dst ) => {
	const sourcePaths = globSync( upath.join( src, '**', '*' ) ).map( path => upath.normalize( path ) );

	for ( const p of sourcePaths ) {
		const strippedPath = p.replace( src, '' );
		const destinationPath = upath.join( dst, strippedPath );

		if ( !fs.existsSync( destinationPath ) ) {
			return;
		}

		const currentStats = fs.statSync( p );
		const cachedStats = fs.statSync( destinationPath );

		if ( currentStats.size !== cachedStats.size ) {
			try {
				fs.copySync( p, destinationPath );
			} catch {
				console.error( `Error when copying file ${ p } to ${ destinationPath }` );
			}
		}
	}
};
