<?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',
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'items' => array(
					'type'  => 'array',
					'items' => array(
						'type'       => 'object',
						'properties' => array(
							'file'    => array( 'type' => 'string' ),
							'name'    => array( 'type' => 'string' ),
							'version' => array( 'type' => 'string' ),
							'active'  => array( 'type' => 'boolean' ),
						),
					),
				),
				'total' => array( 'type' => 'integer' ),
			),
		),
		'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
 */
function wpagent_exec_list_plugins( $input = null ) {
	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 ),
		);
	}

	return array(
		'items' => $items,
		'total' => count( $items ),
	);
}
