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

'use strict';

const { styleText } = require( 'util' );
const upath = require( 'upath' );
const chokidar = require( 'chokidar' );
const { copy } = require( 'fs-extra' );

module.exports = function watchMd( hexoManager ) {
	console.log( styleText( 'yellow', 'Umberto is in watch mode – press CTRL+C to exit.' ) );

	for ( const { originPath, dstPath } of hexoManager.getOriginPaths() ) {
		chokidar
			.watch( originPath, {
				ignoreInitial: true,
				ignored: ( path, stats ) => stats?.isFile() && !path.endsWith( '.md' )
			} )
			.on( 'add', file => copyFile( originPath, dstPath, file ) )
			.on( 'change', file => copyFile( originPath, dstPath, file ) );
	}
};

function copyFile( originPath, dstPath, file ) {
	const dest = upath.join( dstPath, upath.relative( originPath, file ) );

	return copy( file, dest );
}
