<?php

use MediaWiki\Settings\Source\FileSource;
use Wikimedia\StaticArrayWriter;

require_once __DIR__ . '/Maintenance.php';

/**
 * Maintenance script that generates the PHP representation of the config-schema.yaml file.
 *
 * @ingroup Maintenance
 */
class GenerateConfigSchema extends Maintenance {

	/** @var string */
	private const DEFAULT_INPUT_PATH = 'includes/config-schema.yaml';

	/** @var string */
	private const DEFAULT_OUTPUT_PATH = 'includes/config-schema.php';

	public function __construct() {
		parent::__construct();

		$this->addDescription( 'Build config-schema.php file from config-schema.yaml' );
		$this->addOption(
			'schema',
			'Path to the config schema file relative to $IP. Default: ' . self::DEFAULT_INPUT_PATH,
			false,
			true
		);

		$this->addOption(
			'output',
			'Path to output relative to $IP. Default: ' . self::DEFAULT_OUTPUT_PATH,
			false,
			true
		);
	}

	public function execute() {
		$schema = ( new FileSource( $this->getInputPath() ) )->load();

		foreach ( $schema['config-schema'] as $key => &$value ) {
			unset( $value['description'] );
		}

		$content = ( new StaticArrayWriter() )->write(
			$schema,
			"This file is automatically generated using maintenance/generateConfigSchema.php.\n" .
			"phpcs:disable Generic.Files.LineLength"
		);

		file_put_contents( $this->getOutputPath(), $content );
	}

	private function getInputPath(): string {
		global $IP;
		$inputPath = $this->getOption( 'schema', self::DEFAULT_INPUT_PATH );
		return $IP . DIRECTORY_SEPARATOR . $inputPath;
	}

	private function getOutputPath(): string {
		global $IP;
		$outputPath = $this->getOption( 'output', self::DEFAULT_OUTPUT_PATH );
		if ( $outputPath === '-' || $outputPath === 'php://stdout' ) {
			return 'php://stdout';
		}
		return $IP . DIRECTORY_SEPARATOR . $outputPath;
	}
}

$maintClass = GenerateConfigSchema::class;
require_once RUN_MAINTENANCE_IF_MAIN;
