/**
 * @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 readDocSources = require( './read-doc-sources' );
const DataProvider = require( '../data-converter/data-provider' );
const ApiBuilder = require( '../api-builder/api-builder' );
const TemplateCollection = require( '../template/template-collection' );

/**
 * Builds API docs.
 * Reads API raw data (usually generated by JSDoc).
 * Converts that data to format understood by Umberto.
 * Creates ApiBuilder instance to process doclets and render HTML.
 *
 * @param config
 * @returns {Promise<ApiBuilder>}
 */
module.exports = async config => {
	const {
		src,
		projectDst, // e.g.: ckeditor5/latest/api
		outputDir, // build/docs
		themePath, // Umberto theme path
		BASE_PATH, // e.g.: ckeditor5/latest
		docSearch, // Algolia's docsearch config
		templateLocals, // Various data required by templates
		projectConfig, // umberto.json config
		canonicalUrlBeginning,
		macrosVariables
	} = config;

	const apiConfig = projectConfig.groups ? projectConfig.groups.find( g => g.id === 'api-reference' ) : null;
	const middlewares = apiConfig ? apiConfig.middlewares : [];
	const apiType = templateLocals.projectLocals.apiType;
	const docSources = readDocSources( src, apiType );
	const dataProvider = new DataProvider();
	const dataCollection = dataProvider.convert( apiType, docSources, { middlewares } );
	const theme = projectConfig.slug === 'ckeditor5' ? 'gloria' : 'umberto';

	if ( !dataCollection ) {
		console.error( `Could not convert docs data for: ${ projectConfig.name }.` );

		return;
	}

	const templateCol = new TemplateCollection( upath.join( themePath, 'layout', theme, '_api-docs' ), {
		locals: templateLocals
	} );
	const apiBuilder = new ApiBuilder(
		templateCol,
		dataCollection,
		{
			destinationDir: upath.join( outputDir, projectDst ),
			BASE_PATH,
			docSearch,
			projectConfig,
			canonicalUrlBeginning,
			macrosVariables
		}
	);

	console.log( `Building API docs of ${ projectConfig.name }...` );
	console.time( `Built API docs of ${ projectConfig.name } in` );
	const buildInfo = await apiBuilder.buildApi();
	console.timeEnd( `Built API docs of ${ projectConfig.name } in` );

	if ( process.argv.includes( '--strict' ) && buildInfo.warningCount > 0 ) {
		console.log( `There were ${ buildInfo.warningCount } warnings reported in strict mode. Aborting.` );
		process.exit( 1 );
	}

	return apiBuilder;
};
