<?php
/**
 * Plugin Install — server-side execution.
 *
 * Runs the install in-process against WP core's `Plugin_Upgrader` under
 * the App Password user's identity (set by `REST_API::is_basic_authenticated()`
 * before this handler dispatches). Capability checks run as that user
 * via `current_user_can()` so unauthorised roles cannot install.
 *
 * Pre-App-Password versions of this ability returned a js_hook envelope
 * and deferred to the browser session's nonce + cookie path. That dance
 * was the only WP.org-compliant route when the SaaS authenticated with
 * a Sanctum bearer that didn't bind to a WP user. App Password auth
 * (added in feat/app-password-mcp-auth-rp) IS the WP-blessed pattern
 * for third-party services — server-side install with a user-bound
 * credential is fully compliant, returns real success/error in one
 * round-trip, and removes the "dispatched → maybe-done-next-turn"
 * UX gap.
 *
 * @since 0.0.5
 * @package zip-ai
 */

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

use Plugin_Upgrader;
use WP_Ajax_Upgrader_Skin;
use ZipAI\MCP\Classes\Abilities\Abstract_Ability;
use ZipAI\MCP\Classes\Core\Response;
use ZipAI\MCP\Classes\Core\Tool_Types;

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

class PluginInstall extends Abstract_Ability {

	protected $is_destructive = true;

	public function configure() {
		$this->id          = 'zipai/install-plugin';
		$this->label       = 'Install Plugin';
		$this->description = 'Install a plugin from the WordPress.org repository by slug. '
			. 'Runs in-process via `Plugin_Upgrader` under the App-Password user\'s identity. '
			. 'The user must have the `install_plugins` capability (and `activate_plugins` when `status: "active"`). '
			. 'Returns synchronously with the actual result — no browser round-trip.';
		$this->capability  = 'install_plugins';

		$this->meta = array(
			'tool_type' => Tool_Types::WRITE,
		);
	}

	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',
					'pattern'     => '^[a-z0-9][a-z0-9-]*$',
					'description' => 'Plugin slug on WordPress.org (e.g. "contact-form-7", "wordpress-seo"). Lowercase, hyphen-separated. NOT the full plugin path or display name.',
				),
				'status' => array(
					'type'        => 'string',
					'enum'        => array( 'inactive', 'active' ),
					'default'     => 'inactive',
					'description' => 'Optional target state after install. "active" requires `activate_plugins` capability too.',
				),
			),
		);
	}

	public function execute( $args ) {
		$raw_slug = isset( $args['slug'] ) ? (string) $args['slug'] : '';
		if ( '' === trim( $raw_slug ) ) {
			return Response::error( 'Plugin slug is required (e.g. "contact-form-7").' );
		}
		$slug = sanitize_key( $raw_slug );
		// sanitize_key silently strips spaces/casing/punctuation — but an LLM
		// emitting "Bad Slug!" or "../evil" should fail loudly, not get
		// silently rewritten to "badslug" / "evil". Reject when sanitisation
		// changed the input or the result doesn't match the .org slug shape.
		if ( $slug !== $raw_slug || ! preg_match( '/^[a-z0-9][a-z0-9-]*$/', $slug ) ) {
			return Response::error( 'Invalid plugin slug. Use the lowercase, hyphen-separated WordPress.org slug (e.g. "contact-form-7").' );
		}

		// File-mod gate — same WP.org-required check used by core. Honor
		// DISALLOW_FILE_MODS so locked-down sites refuse loudly.
		if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS ) {
			return Response::error( 'Plugin installation is disabled on this site (DISALLOW_FILE_MODS).' );
		}

		$want_active = isset( $args['status'] ) && 'active' === $args['status'];
		if ( $want_active && ! current_user_can( 'activate_plugins' ) ) {
			return Response::error( 'Connected user lacks `activate_plugins` capability — cannot install with status=active.' );
		}

		// WP-Admin upgrader machinery isn't auto-loaded in REST context.
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/misc.php';
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
		require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php';

		// Initialise WP_Filesystem. On FTP-mode hosts without stored
		// credentials this fails — return a clear, actionable error
		// instead of a deep upgrader stack trace.
		if ( ! WP_Filesystem() ) {
			return Response::error(
				'Filesystem credentials required for plugin install. '
				. 'Configure FS_METHOD or store FTP credentials in wp-config.php.'
			);
		}

		// Fetch plugin info from WP.org to obtain the download_link.
		$api = plugins_api( 'plugin_information', array( 'slug' => $slug ) );
		if ( is_wp_error( $api ) ) {
			return Response::error( sprintf( 'Could not fetch plugin "%s" from WP.org: %s', $slug, $api->get_error_message() ) );
		}
		if ( empty( $api->download_link ) ) {
			return Response::error( sprintf( 'Plugin "%s" has no download link on WP.org.', $slug ) );
		}

		// Host allowlist on the WP.org-supplied download URL. `plugins_api()`
		// hits `api.wordpress.org`, but the returned `download_link` is data
		// the network gave us — DNS hijack, TLS-MITM on a host with
		// `ZIPAI_MCP_DISABLE_SSL_VERIFY`, or a transient poisoning of the
		// `plugins_api_result` filter could otherwise smuggle an
		// attacker-controlled archive into `Plugin_Upgrader::install()`
		// under super-admin identity. Hard-pin the host so only
		// `downloads.wordpress.org` archives are honoured.
		$download_host = wp_parse_url( $api->download_link, PHP_URL_HOST );
		if ( 'downloads.wordpress.org' !== $download_host ) {
			return Response::error(
				sprintf(
					'Refusing to install plugin "%s": download host "%s" is not downloads.wordpress.org.',
					$slug,
					is_string( $download_host ) ? $download_host : ''
				)
			);
		}

		$upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
		$result   = $upgrader->install( $api->download_link );

		if ( is_wp_error( $result ) ) {
			return Response::error( sprintf( 'Install failed: %s', $result->get_error_message() ) );
		}
		// `install()` returns null on certain failure paths (filesystem
		// init reset mid-flight, archive extraction issue). Surface as
		// an explicit failure rather than letting it look like success.
		if ( true !== $result ) {
			return Response::error( 'Plugin install did not complete successfully.' );
		}

		$plugin_file = $upgrader->plugin_info();
		if ( ! is_string( $plugin_file ) || '' === $plugin_file ) {
			return Response::error( 'Plugin installed but main file path could not be determined.' );
		}

		$is_active = false;
		if ( $want_active ) {
			$activate_result = activate_plugin( $plugin_file, '', false, true );
			if ( is_wp_error( $activate_result ) ) {
				return Response::error( sprintf( 'Installed but activation failed: %s', $activate_result->get_error_message() ) );
			}
			$is_active = is_plugin_active( $plugin_file );
		}

		wp_clean_plugins_cache();

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

	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' ),
					),
				),
			),
		);
	}
}
