<?php
/**
 * Write Theme File Tool.
 *
 * Write content to a theme file with multiple modes (overwrite, append, prepend,
 * insert, replace). Creates the file if it does not exist. Extends
 * Abstract_File_Writer_Tool for backup system and write modes.
 *
 * @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_Theme_File_Tool class.
 */
class Write_Theme_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_theme_file';
	}

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Write content to a theme 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 theme 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(
				'theme' => array(
					'type'        => 'string',
					'description' => 'Theme stylesheet (directory name) or theme name',
				),
			),
			$params['properties']
		);
		$params['required'][] = 'theme';
		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_themes' );
	}

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

		$theme_slug = trim( $args['theme'] );
		$file       = $args['file'];

		$theme = wp_get_theme( $theme_slug );

		// If not found by stylesheet, search by name
		if ( ! $theme->exists() ) {
			$all_themes = wp_get_themes();
			foreach ( $all_themes as $stylesheet => $t ) {
				if ( stripos( $t->get( 'Name' ), $theme_slug ) !== false ) {
					$theme      = $t;
					$theme_slug = $stylesheet;
					break;
				}
			}
		}

		if ( ! $theme->exists() ) {
			return $this->error_response( "Theme not found: {$theme_slug}" );
		}

		// Get real theme directory path
		$theme_dir      = $theme->get_stylesheet_directory();
		$real_theme_dir = realpath( $theme_dir );
		if ( false === $real_theme_dir ) {
			return $this->error_response( 'Invalid theme directory' );
		}

		// Build target path and validate
		$target_path = $real_theme_dir . DIRECTORY_SEPARATOR . $file;
		$real_path   = PHP_Utils::imaginary_path( $target_path );
		if ( false === $real_path || ! PHP_Utils::is_path_within( $real_path, $real_theme_dir ) ) {
			return $this->error_response( 'Invalid file path: must be within theme 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 theme-specific info to response
		try {
			$data = $this->execute_mode( $real_path, $args );
		} catch ( \Throwable $e ) {
			return $this->error_response( $e->getMessage() );
		}

		$data['theme'] = $theme_slug;
		$data['file']  = $file;

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