/**
 * @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' );

module.exports = ( {
	rootPath,
	defaultRepoUrl,
	packages = []
} ) => {
	const guidesToRepos = {};
	guidesToRepos.default = defaultRepoUrl;

	for ( const item of packages ) {
		const packageRepoUrl = getRepoUrl( upath.join( rootPath, item.path ) );
		globSync( upath.join( rootPath, item.path, 'docs', '**', '*.md' ) )
			.map( p => upath.normalize( p ) )
			.map( p => p.replace( upath.join( rootPath, item.path, 'docs' ), '' ) )
			.forEach( p => {
				guidesToRepos[ p ] = packageRepoUrl;
			} );
	}

	return guidesToRepos;
};

function getRepoUrl( srcDir ) {
	const packageJson = getPackageJson( srcDir );

	if ( packageJson && packageJson.repository ) {
		const match = packageJson.repository.url.match( /http\S*(?=\.git)/ );

		if ( match ) {
			// Handle a mono repository.
			if ( packageJson.repository.directory ) {
				return match[ 0 ] + '/' + packageJson.repository.directory;
			}

			return match[ 0 ];
		}

		return '';
	}

	return '';
}

function getPackageJson( srcDir ) {
	let packageJson = null;

	try {
		packageJson = require( upath.join( srcDir, 'package.json' ) );
	} catch {
		console.warn( `Warning: Cannot read package.json from ${ srcDir }.` );
	}

	return packageJson;
}
