<?php
/**
 * Delegate tool: Routes content creation to Post Creator sub-agent or editing to Editor sub-agent.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

use Agentic_WP\Error_Handler;

defined( 'ABSPATH' ) || exit;

/**
 * Delegate tool for routing content creation to Post Creator sub-agent or editing to Editor sub-agent.
 *
 * @since 1.0.0
 */
class Tool_Delegate_Post_Agent {

	/**
	 * Returns the OpenAI tool schema for delegation.
	 *
	 * @since 1.0.0
	 *
	 * @return array Tool schema definition.
	 */
	public static function schema(): array {
		return array(
			'type'        => 'function',
			'name'        => 'delegate_post_agent',
			'description' => 'Delegate post/page creation to the Post Creator sub-agent, editing to the Editor sub-agent, or interlinking tasks to the Interlinking agent.',
			'parameters'  => array(
				'type'       => 'object',
				'properties' => array(
					'agent'        => array(
						'type'        => 'string',
						'enum'        => array( 'creator', 'editor', 'interlinking', 'meta_description' ),
						'description' => 'Agent type: creator for new posts, editor for modifying existing posts, interlinking for interlinking tasks, meta_description for generating meta descriptions',
					),
					'topic'        => array(
						'type'        => 'string',
						'description' => 'Topic or goal for the post/page.',
					),
					'style'        => array(
						'type'        => 'string',
						'description' => 'Tone or style guidance (optional).',
					),
					'requirements' => array(
						'type'        => 'string',
						'description' => 'Specific requirements, outline, or constraints (optional).',
					),
					'post_id'      => array(
						'type'        => 'integer',
						'description' => 'Post ID (required for editor/meta_description, optional for interlinking)',
					),
					'edit_context' => array(
						'type'        => 'string',
						'description' => 'Additional context for editing tasks (target sections, specific requirements)',
					),
				),
			),
		);
	}

	/**
	 * Executes the delegation tool.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args Tool arguments containing agent type and task details.
	 * @return string JSON response or error message.
	 */
	public static function run( array $args ): string {
		$agent_type   = $args['agent'] ?? 'creator';
		$topic        = isset( $args['topic'] ) ? (string) $args['topic'] : '';
		$style        = isset( $args['style'] ) ? (string) $args['style'] : '';
		$requirements = isset( $args['requirements'] ) ? (string) $args['requirements'] : '';
		$post_id      = $args['post_id'] ?? null;
		$edit_context = $args['edit_context'] ?? '';

		if ( 'editor' === $agent_type ) {
			if ( empty( $post_id ) ) {
				return 'ERROR: post_id required for editor agent';
			}

			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return 'ERROR: insufficient_permissions_edit_post';
			}

			$prompt = "Edit post ID {$post_id}.\n\n";
			if ( ! empty( $topic ) ) {
				$prompt .= "Task: {$topic}\n\n";
			}
			if ( ! empty( $edit_context ) ) {
				$prompt .= "Context: {$edit_context}\n\n";
			}
			if ( ! empty( $style ) ) {
				$prompt .= "Style: {$style}\n\n";
			}
			if ( ! empty( $requirements ) ) {
				$prompt .= "Requirements: {$requirements}\n\n";
			}

			$prompt = trim( $prompt );

			$result = \Agentic_WP\Background_Jobs::schedule_sub_agent_job(
				'post_edit',
				array(
					'prompt' => $prompt,
				)
			);

			if ( empty( $result['job_id'] ) ) {
				Error_Handler::log_error(
					'delegate_post_agent',
					'Failed to schedule post_edit background job',
					array( 'agent_type' => 'editor' )
				);
				return 'ERROR: failed_to_schedule_job';
			}

			return wp_json_encode(
				array(
					'status'    => 'queued',
					'job_id'    => $result['job_id'],
					'action_id' => $result['action_id'],
					'type'      => 'post_edit',
					'message'   => 'Post editing job started in background',
				)
			);
		} elseif ( 'interlinking' === $agent_type ) {
			if ( ! empty( $post_id ) && ! current_user_can( 'edit_post', $post_id ) ) {
				return 'ERROR: insufficient_permissions_read_post';
			}

			$prompt = ! empty( $post_id )
				? "Interlinking task for post ID {$post_id}.\n\n"
				: "Interlinking task.\n\n";
			if ( ! empty( $topic ) ) {
				$prompt .= "Task: {$topic}\n\n";
			}
			if ( ! empty( $edit_context ) ) {
				$prompt .= "Context: {$edit_context}\n\n";
			}
			if ( ! empty( $requirements ) ) {
				$prompt .= "Requirements: {$requirements}\n\n";
			}

			$prompt = trim( $prompt );

			$result = \Agentic_WP\Background_Jobs::schedule_sub_agent_job(
				'post_interlinking',
				array(
					'prompt' => $prompt,
				)
			);

			if ( empty( $result['job_id'] ) ) {
				Error_Handler::log_error(
					'delegate_post_agent',
					'Failed to schedule post_interlinking background job',
					array( 'agent_type' => 'interlinking' )
				);
				return 'ERROR: failed_to_schedule_job';
			}

			return wp_json_encode(
				array(
					'status'    => 'queued',
					'job_id'    => $result['job_id'],
					'action_id' => $result['action_id'],
					'type'      => 'post_interlinking',
					'message'   => 'Interlinking analysis job started in background',
				)
			);
		} elseif ( 'meta_description' === $agent_type ) {
			if ( empty( $post_id ) ) {
				return 'ERROR: post_id required for meta description agent';
			}

			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return 'ERROR: insufficient_permissions_edit_post';
			}

			$prompt = "Generate meta description for post ID {$post_id}.\n\n";
			if ( ! empty( $topic ) ) {
				$prompt .= "Task: {$topic}\n\n";
			}
			if ( ! empty( $edit_context ) ) {
				$prompt .= "Context: {$edit_context}\n\n";
			}
			if ( ! empty( $requirements ) ) {
				$prompt .= "Requirements: {$requirements}\n\n";
			}

			$prompt = trim( $prompt );

			$result = \Agentic_WP\Background_Jobs::schedule_sub_agent_job(
				'meta_description_generate',
				array(
					'prompt'  => $prompt,
					'post_id' => $post_id,
				)
			);

			if ( empty( $result['job_id'] ) ) {
				Error_Handler::log_error(
					'delegate_post_agent',
					'Failed to schedule meta_description_generate background job',
					array( 'agent_type' => 'meta_description' )
				);
				return 'ERROR: failed_to_schedule_job';
			}

			return wp_json_encode(
				array(
					'status'    => 'queued',
					'job_id'    => $result['job_id'],
					'action_id' => $result['action_id'],
					'type'      => 'meta_description_generate',
					'message'   => 'Meta description generation job started in background',
				)
			);
		} else {
			$prompt = trim(
				implode(
					"\n\n",
					array_filter(
						array(
							'' !== $topic ? $topic : 'Create a new WordPress page or post as requested by the user.',
							'' !== $style ? ( 'Style/Tone: ' . $style ) : '',
							'' !== $requirements ? ( 'Requirements: ' . $requirements ) : '',
						)
					)
				)
			);

			$result = \Agentic_WP\Background_Jobs::schedule_sub_agent_job(
				'post_create',
				array(
					'prompt' => $prompt,
				)
			);

			if ( empty( $result['job_id'] ) ) {
				Error_Handler::log_error(
					'delegate_post_agent',
					'Failed to schedule post_create background job',
					array( 'agent_type' => 'creator' )
				);
				return 'ERROR: failed_to_schedule_job';
			}

			return wp_json_encode(
				array(
					'status'    => 'queued',
					'job_id'    => $result['job_id'],
					'action_id' => $result['action_id'],
					'type'      => 'post_create',
					'message'   => 'Post creation job started in background',
				)
			);
		}
	}
}
