<?php
/**
 * Create Plugin Tool.
 *
 * Allows the agent to create a new WordPress plugin with minimal boilerplate.
 * Generates proper plugin header and creates directory structure.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Create_Plugin_Tool class.
 */
class Create_Plugin_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'create_plugin';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Create Plugin', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new WordPress plugin with minimal boilerplate (main PHP file with plugin header).';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'name'        => array(
					'type'        => 'string',
					'description' => 'The plugin name (e.g., "My Custom Plugin")',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'A brief description of the plugin',
				),
				'author'      => array(
					'type'        => 'string',
					'description' => 'Author name (defaults to current user display name)',
				),
				'version'     => array(
					'type'        => 'string',
					'description' => 'Initial version (defaults to "1.0.0")',
				),
				'activate'    => array(
					'type'        => 'boolean',
					'description' => 'Whether to activate the plugin after creation (default: false)',
				),
			),
			'required'   => array( 'name', 'description' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'install_plugins' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		// Check if file modifications are disabled
		if ( ! wp_is_file_mod_allowed( 'plugin_install' ) ) {
			return $this->error_response( 'File modifications are disabled' );
		}

		// Check if file editing is disabled
		if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) {
			return $this->error_response( 'File editing is disabled (DISALLOW_FILE_EDIT is set)' );
		}

		if ( ! isset( $args['name'] ) || empty( trim( $args['name'] ) ) ) {
			return $this->error_response( 'Plugin name is required' );
		}
		if ( ! isset( $args['description'] ) || empty( trim( $args['description'] ) ) ) {
			return $this->error_response( 'Plugin description is required' );
		}

		$name        = sanitize_text_field( $args['name'] );
		$description = sanitize_text_field( $args['description'] );
		$slug        = sanitize_title( $name );
		$version     = isset( $args['version'] ) ? sanitize_text_field( $args['version'] ) : '1.0.0';
		$activate    = isset( $args['activate'] ) ? (bool) $args['activate'] : false;

		// Get author from args or current user
		if ( isset( $args['author'] ) && ! empty( trim( $args['author'] ) ) ) {
			$author = sanitize_text_field( $args['author'] );
		} else {
			$current_user = wp_get_current_user();
			$author       = $current_user->display_name;
		}

		$plugin_dir = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $slug;
		$main_file  = $plugin_dir . DIRECTORY_SEPARATOR . $slug . '.php';

		// Check if plugin directory already exists
		if ( file_exists( $plugin_dir ) ) {
			return $this->error_response( "Plugin directory already exists: {$slug}" );
		}

		// Create plugin directory
		if ( ! wp_mkdir_p( $plugin_dir ) ) {
			return $this->error_response( 'Failed to create plugin directory' );
		}

		// Generate text domain from slug
		$text_domain = $slug;

		// Create plugin header content
		$plugin_content  = "<?php\n";
		$plugin_content .= "/**\n";
		$plugin_content .= " * Plugin Name: {$name}\n";
		$plugin_content .= " * Description: {$description}\n";
		$plugin_content .= " * Version: {$version}\n";
		$plugin_content .= " * Author: {$author}\n";
		$plugin_content .= " * Text Domain: {$text_domain}\n";
		$plugin_content .= " */\n\n";
		$plugin_content .= "// Prevent direct access\n";
		$plugin_content .= "if (!defined('ABSPATH')) {\n";
		$plugin_content .= "    exit;\n";
		$plugin_content .= "}\n";

		// Write main plugin file
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- TODO: possibly migrate to WP_Filesystem later
		if ( file_put_contents( $main_file, $plugin_content ) === false ) {
			// Clean up directory on failure
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- TODO: possibly migrate to WP_Filesystem later
			rmdir( $plugin_dir );
			return $this->error_response( 'Failed to create plugin file' );
		}

		$plugin_file = $slug . DIRECTORY_SEPARATOR . $slug . '.php';
		$result      = array(
			'slug'        => $slug,
			'plugin_file' => $plugin_file,
			'directory'   => $plugin_dir,
			'activated'   => false,
		);

		// Activate if requested
		if ( $activate ) {
			if ( ! function_exists( 'activate_plugin' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}
			$activation_result = activate_plugin( $plugin_file );
			if ( is_wp_error( $activation_result ) ) {
				$result['activation_error'] = $activation_result->get_error_message();
			} else {
				$result['activated'] = true;
			}
		}

		return $this->success_response( 'Plugin created successfully', $result );
	}
}
