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

module.exports = data => {
	const parsed = JSON.parse( data ).doclets;

	if ( !parsed ) {
		console.warn( 'No doclets found in passed data.' );

		return;
	}

	parsed.forEach( ( item, index ) => {
		if ( item.kind === 'event' ) {
			// Remove `event:` from an event name.
			if ( item.name.startsWith( 'event' ) ) {
				item.name = item.name.replace( /^event[:-]/, '' );
			}
		}

		if ( item.classdesc ) {
			const description = item.classdesc;
			delete parsed[ index ].classdesc;
			parsed[ index ].description = description;
		}
		if ( item.meta ) {
			if ( Object.keys( item.meta.code ).length ) {
				const len = ( item.comment.match( /\n/g ) || [] ).length;
				item.file = {
					filePath: upath.join( item.meta.path, item.meta.filename ),
					lineNr: item.meta.lineno - 1 - len,
					len
				};
			} else {
				item.file = {
					filePath: upath.join( item.meta.path, item.meta.filename ),
					lineNr: item.meta.lineno,
					len: ( item.comment.match( /\n/g ) || [] ).length
				};
			}
		}

		const isStaticString = item.scope === 'static' ? 'static-' : '';
		item.extraId = `${ isStaticString }${ item.kind }-${ item.name }`;
	} );

	return parsed;
};
