<?php
/**
 * Ability: wp-agent/list-plugins
 *
 * Read-only. Listet installierte Plugins mit Version und Aktiv-Status, analog
 * zum Plugin-Teil von wp-agent-power/list-extensions, aber als eigene,
 * gegatete Companion-Ability mit eigener Capability-Prüfung
 * (activate_plugins) statt manage_options. Dient als unabhängige
 * Re-Read-Quelle für wp-agent/activate-plugin und wp-agent/deactivate-plugin.
 *
 * @package WPAgentCompanion
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function wpagent_ability_list_plugins(): array {
	return array(
		'label'               => __( 'Plugins auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet installierte Plugins mit Dateipfad, Name, Version und Aktiv-Status.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'additionalProperties' => false,
			'properties'           => array(
				'items' => array(
					'type'     => 'array',
					'maxItems' => 250,
					'items' => array(
						'type'                 => 'object',
						'additionalProperties' => false,
						'properties'           => array(
							'file'    => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 255, 'pattern' => '^[A-Za-z0-9][A-Za-z0-9._/-]*\\.php$' ),
							'name'    => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 200 ),
							'version' => array( 'type' => 'string', 'maxLength' => 100 ),
							'active'  => array( 'type' => 'boolean' ),
						),
						'required'             => array( 'file', 'name', 'version', 'active' ),
					),
				),
				'total' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 250 ),
			),
			'required'   => array( 'items', 'total' ),
		),
		'execute_callback'    => 'wpagent_exec_list_plugins',
		'permission_callback' => 'wpagent_perm_activate_plugins',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input Unused; die Ability nimmt keine Parameter entgegen.
 * @return array|WP_Error
 */
function wpagent_exec_list_plugins( $input = null ) {
	$input_valid = wpagent_builder_read_empty_object_input( $input );
	if ( is_wp_error( $input_valid ) ) {
		return $input_valid;
	}
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}

	$items = array();
	foreach ( get_plugins() as $file => $data ) {
		$items[] = array(
			'file'    => (string) $file,
			'name'    => (string) ( $data['Name'] ?? '' ),
			'version' => (string) ( $data['Version'] ?? '' ),
			'active'  => is_plugin_active( (string) $file ),
		);
	}

	$result = array(
		'items' => $items,
		'total' => count( $items ),
	);
	$output_valid = wpagent_list_plugins_validate_output( $result );
	return is_wp_error( $output_valid ) ? $output_valid : $result;
}

/** @return true|WP_Error */
function wpagent_list_plugins_validate_output( array $result ) {
	if ( array( 'items', 'total' ) !== array_keys( $result ) || ! is_array( $result['items'] ) || count( $result['items'] ) > 250 || ! is_int( $result['total'] ) || $result['total'] !== count( $result['items'] ) ) {
		return wpagent_builder_read_invalid_output();
	}
	foreach ( $result['items'] as $item ) {
		if ( ! is_array( $item ) || array( 'file', 'name', 'version', 'active' ) !== array_keys( $item )
			|| ! wpagent_builder_read_valid_text( $item['file'], 1, 255, '/^[A-Za-z0-9][A-Za-z0-9._\/-]*\\.php$/' )
			|| ! wpagent_builder_read_valid_text( $item['name'], 1, 200 ) || ! wpagent_builder_read_valid_text( $item['version'], 0, 100 ) || ! is_bool( $item['active'] ) ) {
			return wpagent_builder_read_invalid_output();
		}
	}
	return true;
}
