<?php
/**
 * Ability: wp-agent/disable-power
 *
 * Panic switch living in the CORE plugin so the verified core can shut the
 * Developer/Staging power mode (wp-agent-power) off even if that plugin
 * misbehaves. Functional: the execute callback deactivates the wp-agent-power
 * plugin via deactivate_plugins(), so exec-php and every other power ability is
 * unregistered from the next request on. It lives in the core plugin by design,
 * so the kill-switch survives even a misbehaving power plugin.
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_disable_power(): array {
	return array(
		'label'               => __( 'Developer-/Staging-Modus abschalten (Panik)', 'wp-agent-companion' ),
		'description'         => __( 'Panik-Schalter im Kern-Plugin. Deaktiviert den Roh-Zugriffs-Modus (wp-agent-power) sofort, falls installiert.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'expected_active'  => array( 'type' => 'boolean' ),
				'expected_version' => array( 'type' => 'string', 'maxLength' => 255 ),
			),
			'required'             => array( 'expected_active', 'expected_version' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'power_installed' => array( 'type' => 'boolean' ),
				'power_active'    => array( 'type' => 'boolean' ),
				'version'         => array( 'type' => 'string' ),
				'disabled'        => array( 'type' => 'boolean' ),
				'note'            => array( 'type' => 'string' ),
			),
			'required'             => array( 'power_installed', 'power_active', 'version', 'disabled', 'note' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_disable_power',
		'permission_callback' => 'wpagent_perm_activate_plugins',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => false,
				'destructive' => false,
				'idempotent'  => false,
			),
		),
	);
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_disable_power( $input = null ) {
	$input = is_array( $input ) ? $input : array();
	$slug = 'wp-agent-power/wp-agent-power.php';
	if ( ! function_exists( 'get_plugins' ) ) {
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
	}
	$state = static function () use ( $slug ): array {
		$plugins = get_plugins();
		$plugin = $plugins[ $slug ] ?? null;
		return array(
			'installed' => is_array( $plugin ),
			'active'    => is_plugin_active( $slug ),
			'version'   => is_array( $plugin ) ? (string) ( $plugin['Version'] ?? '' ) : '',
		);
	};
	$current = $state();
	if ( ! is_bool( $input['expected_active'] ?? null ) || ! is_string( $input['expected_version'] ?? null ) || (bool) $input['expected_active'] !== $current['active'] || ! hash_equals( (string) $input['expected_version'], $current['version'] ) ) {
		return new WP_Error( 'wpagent_disable_power_conflict', __( 'Der Power-Modus änderte sich seit dem Lesen. Lies den Plugin-Zustand neu.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$lock = wpagent_core_mutator_acquire_lock( 'plugin', $slug );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$current = $state();
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Die Berechtigung änderte sich während der Sperrübernahme.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		if ( (bool) $input['expected_active'] !== $current['active'] || ! hash_equals( (string) $input['expected_version'], $current['version'] ) ) {
			return new WP_Error( 'wpagent_disable_power_conflict', __( 'Der Power-Modus änderte sich seit dem Lesen. Lies den Plugin-Zustand neu.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( $current['active'] ) {
			if ( ! wpagent_core_mutator_refresh_lock( 'plugin', $slug, $lock ) ) {
				return new WP_Error( 'wpagent_disable_power_busy', __( 'Die Plugin-Sperre ging vor der Deaktivierung verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			try {
				deactivate_plugins( $slug );
			} catch ( \Throwable ) {
				return wpagent_core_mutator_recovery_required( 'wpagent_disable_power_recovery_required', __( 'Der Power-Modus endete während der Deaktivierung nicht eindeutig. Prüfe den Plugin-Zustand manuell.', 'wp-agent-companion' ), wpagent_core_mutator_hash( $state() ) );
			}
		}
		$fresh = $state();
		if ( $fresh['active'] || ! hash_equals( $current['version'], $fresh['version'] ) || ! wpagent_core_mutator_lock_is_owned( 'plugin', $slug, $lock ) ) {
			return wpagent_core_mutator_recovery_required( 'wpagent_disable_power_recovery_required', __( 'Der Power-Modus konnte nach der Deaktivierung nicht eindeutig bestätigt werden. Prüfe den Plugin-Zustand manuell.', 'wp-agent-companion' ), wpagent_core_mutator_hash( $fresh ) );
		}
		return array(
			'power_installed' => $fresh['installed'],
			'power_active'    => false,
			'version'         => $fresh['version'],
			'disabled'        => true,
			'note'            => $current['active'] ? __( 'wp-agent-power wurde deaktiviert.', 'wp-agent-companion' ) : __( 'wp-agent-power war bereits deaktiviert oder nicht installiert.', 'wp-agent-companion' ),
		);
	} finally {
		wpagent_core_mutator_release_lock( 'plugin', $slug, $lock );
	}
}
