<?php
/**
 * Plugin Activate — server-side execution.
 *
 * Runs `activate_plugin()` in-process under the App Password user's
 * identity (set by `REST_API::is_basic_authenticated()`). The legacy
 * js_hook delegation was needed when the SaaS used a Sanctum bearer
 * not bound to a WP user; App Password auth is the WP-blessed pattern
 * for third-party services and binds capability checks natively.
 *
 * Idempotent — already-active plugins return success without re-firing
 * activation hooks.
 *
 * @since 0.0.5
 * @package zip-ai
 */

namespace ZipAI\MCP\Classes\Abilities\Zipai\System;

use ZipAI\MCP\Classes\Abilities\Abstract_Ability;
use ZipAI\MCP\Classes\Abilities\Zipai\System\PluginResolver;
use ZipAI\MCP\Classes\Core\Response;
use ZipAI\MCP\Classes\Core\Tool_Types;

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

class PluginActivate extends Abstract_Ability {

	protected $is_destructive = true;

	public function configure() {
		$this->id          = 'zipai/activate-plugin';
		$this->label       = 'Activate Plugin';
		$this->description = 'Activate an already-installed plugin by slug or "folder/file" identifier. '
			. 'Runs `activate_plugin()` in-process under the App-Password user\'s identity. '
			. 'Requires `activate_plugins` capability. '
			. 'Accepts a bare slug ("contact-form-7") or the WP REST plugin id "folder/file" with or without `.php` — extension is normalised.';
		$this->capability  = 'activate_plugins';

		$this->meta = array(
			'tool_type'          => Tool_Types::WRITE,
			'preflight_resource' => array(
				'kind'      => 'installed_plugin',
				'arg_field' => 'slug',
			),
		);
	}

	public function get_tool_type() {
		return Tool_Types::WRITE;
	}

	public function get_input_schema() {
		return array(
			'type'                 => 'object',
			'required'             => array( 'slug' ),
			'additionalProperties' => false,
			'properties'           => array(
				'slug' => array(
					'type'        => 'string',
					'description' => 'Plugin slug ("contact-form-7") or WP REST plugin id "folder/file" (`.php` extension optional, stripped automatically).',
				),
			),
		);
	}

	public function execute( $args ) {
		$slug = isset( $args['slug'] ) ? sanitize_text_field( $args['slug'] ) : '';
		if ( '' === $slug ) {
			return Response::error( 'Plugin slug is required.' );
		}
		if ( ! preg_match( '#^[a-z0-9][a-z0-9-]*(?:/[a-z0-9._-]+(?:\.php)?)?$#i', $slug ) ) {
			return Response::error( 'Invalid plugin identifier. Use the slug ("contact-form-7") or the WP REST plugin id "folder/file".' );
		}

		require_once ABSPATH . 'wp-admin/includes/plugin.php';

		$plugin_file = PluginResolver::resolve_plugin_file( $slug );
		if ( null === $plugin_file ) {
			return Response::error( sprintf( 'Plugin "%s" is not installed.', $slug ) );
		}

		if ( is_plugin_active( $plugin_file ) ) {
			return array(
				'success' => true,
				'message' => sprintf( 'Plugin "%s" is already active.', $slug ),
				'data'    => array(
					'slug'        => $slug,
					'plugin_file' => $plugin_file,
					'active'      => true,
				),
			);
		}

		$result = activate_plugin( $plugin_file, '', false, true );
		if ( is_wp_error( $result ) ) {
			return Response::error( sprintf( 'Activation failed: %s', $result->get_error_message() ) );
		}

		// Belt-and-braces verify — `activate_plugin()` returns `null` on
		// success but a fatal activation error can leave the plugin
		// inactive without surfacing a WP_Error. Probe state explicitly.
		if ( ! is_plugin_active( $plugin_file ) ) {
			return Response::error( sprintf( 'Plugin "%s" did not activate (no error returned, but plugin remains inactive).', $slug ) );
		}

		return array(
			'success' => true,
			'message' => sprintf( 'Plugin "%s" activated.', $slug ),
			'data'    => array(
				'slug'        => $slug,
				'plugin_file' => $plugin_file,
				'active'      => true,
			),
		);
	}

	public function get_output_schema() {
		return array(
			'type'                 => 'object',
			'required'             => array( 'success' ),
			'additionalProperties' => true,
			'properties'           => array(
				'success' => array( 'type' => 'boolean' ),
				'message' => array( 'type' => 'string' ),
				'data'    => array(
					'type'       => 'object',
					'properties' => array(
						'slug'        => array( 'type' => 'string' ),
						'plugin_file' => array( 'type' => 'string' ),
						'active'      => array( 'type' => 'boolean' ),
					),
				),
			),
		);
	}
}
