<?php

namespace AtlasAiDev\Awfah\REST;

use AtlasAiDev\Awfah\Service\AI_Provider_Manager;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

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

/**
 * REST controller for managing AI prompts (global and per-post)
 * and generation history.
 */
class Prompts_Controller extends WP_REST_Controller {

	/**
	 * Allowed tool slugs for prompt storage.
	 *
	 * @var string[]
	 */
	private const ALLOWED_TOOLS = [
		'generate-excerpt',
		'suggest-titles',
		'summarization',
		'image-generation',
		'alt-text-generation',
	];

	/**
	 * Maximum number of history entries per tool per post.
	 *
	 * @var int
	 */
	private const MAX_HISTORY = 5;

	public function __construct() {
		$this->namespace = 'awfah/v1';
		$this->rest_base = 'prompts';
	}

	public function register_routes(): void {
		// Global prompt: GET / POST.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<tool_slug>[a-z0-9-]+)',
			[
				[
					'methods'             => 'GET',
					'callback'            => [ $this, 'get_global_prompt' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => $this->get_tool_slug_args(),
				],
				[
					'methods'             => 'POST',
					'callback'            => [ $this, 'save_global_prompt' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => array_merge(
						$this->get_tool_slug_args(),
						[
							'prompt' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_textarea_field',
							],
						]
					),
				],
			]
		);

		// Per-post prompt: GET / POST.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<tool_slug>[a-z0-9-]+)/(?P<post_id>[\d]+)',
			[
				[
					'methods'             => 'GET',
					'callback'            => [ $this, 'get_post_prompt' ],
					'permission_callback' => [ $this, 'permissions_check_post' ],
					'args'                => $this->get_post_args(),
				],
				[
					'methods'             => 'POST',
					'callback'            => [ $this, 'save_post_prompt' ],
					'permission_callback' => [ $this, 'permissions_check_post' ],
					'args'                => array_merge(
						$this->get_post_args(),
						[
							'prompt' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_textarea_field',
							],
						]
					),
				],
			]
		);

		// Per-post generation history: GET / POST.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<tool_slug>[a-z0-9-]+)/(?P<post_id>[\d]+)/history',
			[
				[
					'methods'             => 'GET',
					'callback'            => [ $this, 'get_history' ],
					'permission_callback' => [ $this, 'permissions_check_post' ],
					'args'                => $this->get_post_args(),
				],
				[
					'methods'             => 'POST',
					'callback'            => [ $this, 'save_history_entry' ],
					'permission_callback' => [ $this, 'permissions_check_post' ],
					'args'                => array_merge(
						$this->get_post_args(),
						[
							'result' => [
								'type'     => 'string',
								'required' => true,
								'sanitize_callback' => 'sanitize_textarea_field',
							],
							'prompt' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_textarea_field',
								'default'           => '',
							],
							'tone' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
								'default'           => '',
							],
							'provider' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
								'default'           => 'auto',
							],
							'style' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
								'default'           => '',
							],
							'image_id' => [
								'type'              => 'integer',
								'sanitize_callback' => 'absint',
								'default'           => 0,
							],
							'image_url' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_url',
								'default'           => '',
							],
						]
					),
				],
			]
		);

		// Prompt templates: GET / POST / DELETE.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<tool_slug>[a-z0-9-]+)/templates',
			[
				[
					'methods'             => 'GET',
					'callback'            => [ $this, 'get_templates' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => $this->get_tool_slug_args(),
				],
				[
					'methods'             => 'POST',
					'callback'            => [ $this, 'create_template' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => array_merge(
						$this->get_tool_slug_args(),
						[
							'name' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_text_field',
							],
							'prompt' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_textarea_field',
							],
						]
					),
				],
				[
					'methods'             => 'DELETE',
					'callback'            => [ $this, 'delete_template' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => array_merge(
						$this->get_tool_slug_args(),
						[
							'template_id' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_text_field',
							],
						]
					),
				],
			]
		);

		// Explain generation: POST.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<tool_slug>[a-z0-9-]+)/explain',
			[
				[
					'methods'             => 'POST',
					'callback'            => [ $this, 'explain_generation' ],
					'permission_callback' => [ $this, 'permissions_check' ],
					'args'                => array_merge(
						$this->get_tool_slug_args(),
						[
							'result' => [
								'type'              => 'string',
								'required'          => true,
								'sanitize_callback' => 'sanitize_textarea_field',
							],
							'prompt' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_textarea_field',
								'default'           => '',
							],
							'tone' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
								'default'           => '',
							],
							'style' => [
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
								'default'           => '',
							],
						]
					),
				],
			]
		);
	}

	/**
	 * Permission check: user can edit posts.
	 */
	public function permissions_check(): bool {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Permission check: user can edit the specific post.
	 */
	public function permissions_check_post( WP_REST_Request $request ) {
		$post_id = (int) $request->get_param( 'post_id' );

		if ( ! $post_id || ! get_post( $post_id ) ) {
			return new WP_Error(
				'rest_post_not_found',
				__( 'Post not found.', 'ai-workflow-automation-ai-agent-hub' ),
				[ 'status' => 404 ]
			);
		}

		return current_user_can( 'edit_post', $post_id );
	}

	/**
	 * GET global prompt.
	 */
	public function get_global_prompt( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$option    = get_option( "awfah_prompt_{$tool_slug}", '' );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'prompt'    => (string) $option,
			'scope'     => 'global',
		] );
	}

	/**
	 * POST save global prompt.
	 */
	public function save_global_prompt( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$prompt    = $request->get_param( 'prompt' );

		update_option( "awfah_prompt_{$tool_slug}", $prompt, false );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'prompt'    => $prompt,
			'scope'     => 'global',
			'saved'     => true,
		] );
	}

	/**
	 * GET per-post prompt.
	 */
	public function get_post_prompt( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$post_id   = (int) $request->get_param( 'post_id' );
		$prompt    = get_post_meta( $post_id, "_awfah_prompt_{$tool_slug}", true );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'post_id'   => $post_id,
			'prompt'    => (string) $prompt,
			'scope'     => 'post',
		] );
	}

	/**
	 * POST save per-post prompt.
	 */
	public function save_post_prompt( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$post_id   = (int) $request->get_param( 'post_id' );
		$prompt    = $request->get_param( 'prompt' );

		update_post_meta( $post_id, "_awfah_prompt_{$tool_slug}", $prompt );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'post_id'   => $post_id,
			'prompt'    => $prompt,
			'scope'     => 'post',
			'saved'     => true,
		] );
	}

	/**
	 * GET generation history for a post.
	 */
	public function get_history( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$post_id   = (int) $request->get_param( 'post_id' );
		$history   = get_post_meta( $post_id, "_awfah_history_{$tool_slug}", true );

		if ( ! is_array( $history ) ) {
			$history = [];
		}

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'post_id'   => $post_id,
			'history'   => $history,
		] );
	}

	/**
	 * POST add a generation history entry.
	 */
	public function save_history_entry( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$post_id   = (int) $request->get_param( 'post_id' );

		// Get existing history.
		$history = get_post_meta( $post_id, "_awfah_history_{$tool_slug}", true );
		if ( ! is_array( $history ) ) {
			$history = [];
		}

		// Build new entry.
		$entry = [
			'result'    => $request->get_param( 'result' ),
			'prompt'    => $request->get_param( 'prompt' ),
			'tone'      => $request->get_param( 'tone' ),
			'style'     => $request->get_param( 'style' ),
			'provider'  => $request->get_param( 'provider' ),
			'image_id'  => $request->get_param( 'image_id' ),
			'image_url' => $request->get_param( 'image_url' ),
			'timestamp' => current_time( 'mysql' ),
		];

		// Prepend new entry (most recent first).
		array_unshift( $history, $entry );

		// Keep only the last N entries.
		$history = array_slice( $history, 0, self::MAX_HISTORY );

		// Save immediately.
		update_post_meta( $post_id, "_awfah_history_{$tool_slug}", $history );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'post_id'   => $post_id,
			'history'   => $history,
			'saved'     => true,
		] );
	}

	/**
	 * GET all templates (pre-built + custom) for a tool.
	 */
	public function get_templates( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$prebuilt  = $this->get_prebuilt_templates( $tool_slug );
		$custom    = get_option( "awfah_templates_{$tool_slug}", [] );

		if ( ! is_array( $custom ) ) {
			$custom = [];
		}

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'templates' => array_merge( $prebuilt, $custom ),
		] );
	}

	/**
	 * POST create a custom template.
	 */
	public function create_template( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$name      = $request->get_param( 'name' );
		$prompt    = $request->get_param( 'prompt' );

		$custom = get_option( "awfah_templates_{$tool_slug}", [] );
		if ( ! is_array( $custom ) ) {
			$custom = [];
		}

		$new_template = [
			'id'          => wp_generate_uuid4(),
			'name'        => $name,
			'prompt'      => $prompt,
			'is_prebuilt' => false,
			'created_at'  => current_time( 'mysql' ),
		];

		$custom[] = $new_template;
		update_option( "awfah_templates_{$tool_slug}", $custom, false );

		$prebuilt = $this->get_prebuilt_templates( $tool_slug );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'templates' => array_merge( $prebuilt, $custom ),
			'created'   => $new_template,
		] );
	}

	/**
	 * DELETE a custom template by ID.
	 */
	public function delete_template( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug   = $request->get_param( 'tool_slug' );
		$template_id = $request->get_param( 'template_id' );

		$custom = get_option( "awfah_templates_{$tool_slug}", [] );
		if ( ! is_array( $custom ) ) {
			$custom = [];
		}

		$custom = array_values( array_filter( $custom, static function ( $t ) use ( $template_id ) {
			return $t['id'] !== $template_id;
		} ) );

		update_option( "awfah_templates_{$tool_slug}", $custom, false );

		$prebuilt = $this->get_prebuilt_templates( $tool_slug );

		return new WP_REST_Response( [
			'tool_slug' => $tool_slug,
			'templates' => array_merge( $prebuilt, $custom ),
			'deleted'   => true,
		] );
	}

	/**
	 * POST explain why the AI generated a particular result.
	 */
	public function explain_generation( WP_REST_Request $request ): WP_REST_Response {
		$tool_slug = $request->get_param( 'tool_slug' );
		$result    = $request->get_param( 'result' );
		$prompt    = $request->get_param( 'prompt' );
		$tone      = $request->get_param( 'tone' );
		$style     = $request->get_param( 'style' );

		$modifier = $tone ? "Tone: {$tone}. " : '';
		$modifier .= $style ? "Style: {$style}. " : '';

		$meta_prompt = "You are an AI assistant explaining your own generation process.\n\n"
			. "The user used the \"{$tool_slug}\" tool with the following parameters:\n"
			. "- System prompt: {$prompt}\n"
			. ( $modifier ? "- Modifiers: {$modifier}\n" : '' )
			. "\nThe AI generated this result:\n<result>\n{$result}\n</result>\n\n"
			. "Explain in 2-3 concise sentences why this particular result was generated. "
			. "Focus on how the prompt, modifiers, and content influenced the output. "
			. "Be specific and helpful.";

		$explanation = AI_Provider_Manager::generate_text( $meta_prompt, [
			'temperature' => 0.3,
		] );

		if ( empty( $explanation ) ) {
			return new WP_REST_Response( [
				'explanation' => __( 'Unable to generate explanation. Please check your AI provider configuration.', 'ai-workflow-automation-ai-agent-hub' ),
			] );
		}

		return new WP_REST_Response( [
			'explanation' => $explanation,
		] );
	}

	/**
	 * Get pre-built templates for a tool.
	 *
	 * @param string $tool_slug Tool slug.
	 * @return array Pre-built templates.
	 */
	private function get_prebuilt_templates( string $tool_slug ): array {
		$templates = [
			'generate-excerpt' => [
				[
					'id'          => 'prebuilt-seo-meta',
					'name'        => __( 'SEO Meta Description', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate a concise SEO meta description (150-160 characters) that includes the primary keyword and a compelling call-to-action. Return only the description text.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-social-teaser',
					'name'        => __( 'Social Media Teaser', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Write a short, engaging social media teaser (1-2 sentences) that creates curiosity and encourages clicks. Use conversational language. Return only the teaser text.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-newsletter',
					'name'        => __( 'Newsletter Preview', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Write a brief newsletter preview paragraph (2-3 sentences) that summarizes the key takeaways and entices readers to read the full article. Return only the preview text.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-product-summary',
					'name'        => __( 'Product Summary', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate a product-focused summary (2-3 sentences) highlighting key features and benefits. Use clear, persuasive language. Return only the summary text.',
					'is_prebuilt' => true,
				],
			],
			'image-generation' => [
				[
					'id'          => 'prebuilt-blog-header',
					'name'        => __( 'Blog Header', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Create a professional blog header image that visually represents the article topic. Use clean, modern design with good visual hierarchy suitable for a 16:9 aspect ratio.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-social-banner',
					'name'        => __( 'Social Media Banner', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Create an eye-catching social media banner image that is bold, colorful, and attention-grabbing. Suitable for sharing on Twitter, Facebook, and LinkedIn.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-product-showcase',
					'name'        => __( 'Product Showcase', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Create a clean product showcase image with a neutral background that highlights the product or service described in the content. Professional studio lighting style.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-minimalist-design',
					'name'        => __( 'Minimalist Design', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Create a minimalist featured image with simple shapes, limited color palette, and plenty of white space. Focus on elegant simplicity that conveys the essence of the content.',
					'is_prebuilt' => true,
				],
			],
			'summarization' => [
				[
					'id'          => 'prebuilt-executive-summary',
					'name'        => __( 'Executive Summary', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate a professional executive summary suitable for business stakeholders. Focus on key outcomes, actionable insights, and strategic value. 2-3 sentences.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-key-takeaways',
					'name'        => __( 'Key Takeaways', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Summarize the main takeaways and lessons from this content. What should readers remember? Use clear, direct language. 2-3 sentences.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-eli5',
					'name'        => __( 'ELI5 (Simple Language)', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Explain this content in very simple, everyday language that anyone can understand. Avoid jargon and technical terms. 2-3 sentences.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-technical-abstract',
					'name'        => __( 'Technical Abstract', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate a technical abstract with precise terminology. Cover the methodology, findings, and implications. Suitable for academic or technical audiences. 3-4 sentences.',
					'is_prebuilt' => true,
				],
			],
			'suggest-titles' => [
				[
					'id'          => 'prebuilt-seo-optimized',
					'name'        => __( 'SEO-Optimized', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate SEO-optimized titles that include primary keywords naturally. Focus on search intent and include power words. Max 60 characters each.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-listicle',
					'name'        => __( 'Listicle Style', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate numbered list-style titles (e.g. "7 Ways to...", "Top 10..."). Make them specific and promise clear value.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-how-to',
					'name'        => __( 'How-To Guide', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate instructional "How to" titles that promise practical, step-by-step guidance.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-clickbait-free',
					'name'        => __( 'Clickbait-Free', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate straightforward, honest titles that accurately describe the content. No sensationalism.',
					'is_prebuilt' => true,
				],
			],
			'alt-text-generation' => [
				[
					'id'          => 'prebuilt-descriptive',
					'name'        => __( 'Detailed Descriptive', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Describe the image in detail including all visible elements, people, objects, colors, and spatial arrangement.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-concise',
					'name'        => __( 'Ultra-Concise', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate extremely brief alt text (under 50 characters). Focus only on the single most important element.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-seo-alt',
					'name'        => __( 'SEO-Optimized Alt Text', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Generate alt text that naturally includes relevant keywords while remaining accessible.',
					'is_prebuilt' => true,
				],
				[
					'id'          => 'prebuilt-decorative-check',
					'name'        => __( 'Decorative Image Check', 'ai-workflow-automation-ai-agent-hub' ),
					'prompt'      => 'Determine if this image is decorative or informative. If decorative, return empty alt text. If informative, describe it.',
					'is_prebuilt' => true,
				],
			],
		];

		return $templates[ $tool_slug ] ?? [];
	}

	/**
	 * Validate tool_slug parameter.
	 */
	private function get_tool_slug_args(): array {
		return [
			'tool_slug' => [
				'type'              => 'string',
				'required'          => true,
				'sanitize_callback' => 'sanitize_text_field',
				'validate_callback' => function ( $value ) {
					if ( ! in_array( $value, self::ALLOWED_TOOLS, true ) ) {
						return new WP_Error(
							'rest_invalid_tool_slug',
							/* translators: %s: tool slug. */
							sprintf( __( 'Invalid tool slug: %s', 'ai-workflow-automation-ai-agent-hub' ), $value ),
							[ 'status' => 400 ]
						);
					}
					return true;
				},
			],
		];
	}

	/**
	 * Args for routes with post_id.
	 */
	private function get_post_args(): array {
		return array_merge(
			$this->get_tool_slug_args(),
			[
				'post_id' => [
					'type'              => 'integer',
					'required'          => true,
					'sanitize_callback' => 'absint',
				],
			]
		);
	}
}
