<?php
/**
 * Write Plugin File Tool.
 *
 * Write content to a plugin file. Creates the file if it does not exist.
 * Extends Abstract_File_Writer_Tool for backup system and write modes
 * (overwrite, append, prepend, insert_at_line).
 *
 * @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;
}

/**
 * Write_Plugin_File_Tool class.
 */
class Write_Plugin_File_Tool extends Abstract_File_Writer_Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Write content to a plugin file.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return parent::get_instructions() . ' File path is relative to the plugin directory. Creates file if it does not exist.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		$params               = parent::get_parameters();
		$params['properties'] = array_merge(
			array(
				'plugin' => array(
					'type'        => 'string',
					'description' => 'Plugin slug (directory name) or main plugin file path',
				),
			),
			$params['properties']
		);
		$params['required'][] = 'plugin';
		return $params;
	}

	/**
	 * 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( 'edit_plugins' );
	}

	/**
	 * 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( 'capability_edit_plugins' ) ) {
			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['plugin'] ) || empty( trim( $args['plugin'] ) ) ) {
			return $this->error_response( 'Plugin identifier is required' );
		}
		if ( ! isset( $args['file'] ) || empty( trim( $args['file'] ) ) ) {
			return $this->error_response( 'File path is required' );
		}

		// Find the plugin using WordPress's plugin registry
		$plugin = WordPress_Utils::find_plugin( $args['plugin'] );
		if ( null === $plugin ) {
			return $this->error_response( 'Plugin not found: ' . $args['plugin'] );
		}

		$slug       = WordPress_Utils::get_plugin_slug( $plugin['file'] );
		$file       = $args['file'];
		$plugin_dir = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $slug;

		// Get real plugin directory path
		$real_plugin_dir = realpath( $plugin_dir );
		if ( false === $real_plugin_dir ) {
			return $this->error_response( 'Invalid plugin directory' );
		}

		// Build target path and validate
		$target_path = $real_plugin_dir . DIRECTORY_SEPARATOR . $file;
		$real_path   = PHP_Utils::imaginary_path( $target_path );
		if ( false === $real_path || ! PHP_Utils::is_path_within( $real_path, $real_plugin_dir ) ) {
			return $this->error_response( 'Invalid file path: must be within plugin directory' );
		}

		// Create subdirectories if needed
		$dir = dirname( $real_path );
		if ( ! is_dir( $dir ) ) {
			if ( ! wp_mkdir_p( $dir ) ) {
				return $this->error_response( 'Failed to create directory structure' );
			}
		}

		// Execute write operation and add plugin-specific info to response
		try {
			$data = $this->execute_mode( $real_path, $args );
		} catch ( \Throwable $e ) {
			return $this->error_response( $e->getMessage() );
		}

		$data['plugin'] = $slug;
		$data['file']   = $file;

		return $this->success_response( 'File written successfully', $data );
	}
}
