<?php

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

class AIEO_SEO_AI_Assist {

	const NONCE  = 'aieo_seo_ai_assist';
	const ACTION = 'aieo_seo_ai_suggest';

	public static function register() {
		add_action( 'wp_ajax_' . self::ACTION, array( __CLASS__, 'ajax_suggest' ) );
	}

	
	public static function available() {
		return class_exists( 'AI_eShop_Chat_Anthropic_API' ) && '' !== (string) get_option( 'aieo_rooster_api_key', '' );
	}

	public static function ajax_suggest() {
		if ( ! check_ajax_referer( self::NONCE, 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'ai-eshop-optimizer' ) ) );
		}
		$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
		if ( $post_id <= 0 || ! current_user_can( 'edit_post', $post_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-eshop-optimizer' ) ) );
		}
		if ( ! self::available() ) {
			wp_send_json_error( array( 'message' => __( 'AI is not configured — paste the Rooster Content Connector token in the Pro Panel.', 'ai-eshop-optimizer' ) ) );
		}
		$post = get_post( $post_id );
		if ( ! $post instanceof WP_Post ) {
			wp_send_json_error( array( 'message' => __( 'Object not found.', 'ai-eshop-optimizer' ) ) );
		}
		$res = self::suggest( $post );
		if ( is_wp_error( $res ) ) {
			wp_send_json_error( array( 'message' => $res->get_error_message() ) );
		}
		wp_send_json_success( $res );
	}

	
	public static function suggest( $post, array $extra_context = array() ) {
		$ctx  = self::context( $post );
		$api  = AI_eShop_Chat_Anthropic_API::get_instance(); 
		$user = self::user_prompt( $ctx );
		if ( ! empty( $extra_context ) ) {
			$user .= "\n\n" . implode( "\n", array_map( 'strval', $extra_context ) )
				. "\nWrite the title/description to WIN clicks against the SERP above (differentiate, don't imitate). Return the JSON now.";
		}
		$resp = $api->chat_completion(
			array( array( 'role' => 'user', 'content' => $user ) ),
			array(
				'system'      => self::system_prompt(),
				'max_tokens'  => 800,
				'temperature' => 0.6,
			)
		);
		if ( is_wp_error( $resp ) ) {
			return $resp;
		}

		$text = '';
		if ( isset( $resp['content'] ) && is_array( $resp['content'] ) ) {
			foreach ( $resp['content'] as $blk ) {
				if ( is_array( $blk ) && 'text' === ( $blk['type'] ?? '' ) && isset( $blk['text'] ) ) {
					$text .= (string) $blk['text'];
				}
			}
		}
		$data = self::parse_json( $text );
		if ( ! is_array( $data ) ) {
			return new WP_Error( 'aieo_ai_parse', __( 'The AI returned an unexpected format. Please try again.', 'ai-eshop-optimizer' ) );
		}

		return array(
			'title'       => self::clean( $data['title'] ?? '', 70 ),
			'description' => self::clean( $data['description'] ?? '', 200 ),
			'keyphrase'   => self::clean( $data['keyphrase'] ?? '', 80 ),
		);
	}

	
	
	

	private static function system_prompt() {
		return implode( ' ', array(
			'You are an expert e-commerce SEO copywriter.',
			'Given a product or article and its commerce context, produce the best on-page SEO metadata to win high-intent organic clicks.',
			'Rules: SEO title <= 60 characters, compelling, includes the focus keyphrase and (for products) the brand when natural.',
			'Meta description 120-160 characters, benefit-led, with a soft call to action.',
			'keyphrase = the exact high-intent search phrase a ready-to-buy shopper would type (not the bare product name; reflect intent/use/brand).',
			'Write in the SAME language as the provided content (Greek content -> Greek output).',
			'Do NOT invent facts, prices, or claims not supported by the context. No emoji, no ALL-CAPS, no quotes around the whole title.',
			'Return ONLY a single minified JSON object with keys: title, description, keyphrase. No markdown, no code fences, no commentary.',
		) );
	}

	private static function user_prompt( $ctx ) {
		$lines = array();
		$lines[] = 'TYPE: ' . $ctx['type'];
		$lines[] = 'SITE: ' . $ctx['site'];
		$lines[] = 'LANGUAGE (locale): ' . $ctx['locale'];
		$lines[] = 'NAME: ' . $ctx['name'];
		if ( '' !== $ctx['brand'] ) {
			$lines[] = 'BRAND: ' . $ctx['brand'];
		}
		if ( '' !== $ctx['categories'] ) {
			$lines[] = 'CATEGORIES: ' . $ctx['categories'];
		}
		if ( '' !== $ctx['price'] ) {
			$lines[] = 'PRICE: ' . $ctx['price'] . ( $ctx['in_stock'] ? ' (in stock)' : ' (out of stock)' );
		}
		$lines[] = 'POPULARITY (real sales demand, 0-100): ' . $ctx['demand'] . ' — ' . $ctx['demand_label'];
		if ( '' !== $ctx['excerpt'] ) {
			$lines[] = 'SUMMARY: ' . $ctx['excerpt'];
		}
		$lines[] = '';
		
		
		$lines[] = 'CURRENT SEO (may be empty) — title: ' . wp_json_encode( $ctx['cur_title'] )
			. '; description: ' . wp_json_encode( $ctx['cur_desc'] )
			. '; keyphrase: ' . wp_json_encode( $ctx['cur_kp'] ) . '.';
		$lines[] = 'Improve on the current values. Return the JSON now.';
		return implode( "\n", $lines );
	}

	private static function context( $post ) {
		$type    = (string) $post->post_type;
		$post_id = (int) $post->ID;
		$row     = class_exists( 'AIEO_SEO_Store' ) ? (array) AIEO_SEO_Store::get( $type, $post_id ) : array();

		$excerpt = wp_strip_all_tags( (string) ( $post->post_excerpt ?: $post->post_content ) );
		$excerpt = self::clean( $excerpt, 500 );

		$brand = '';
		$cats  = '';
		$price = '';
		$stock = true;
		if ( 'product' === $type && function_exists( 'wc_get_product' ) ) {
			$brands = get_the_terms( $post_id, 'product_brand' );
			if ( $brands && ! is_wp_error( $brands ) ) {
				$brand = (string) $brands[0]->name;
			}
			$cat_terms = get_the_terms( $post_id, 'product_cat' );
			if ( $cat_terms && ! is_wp_error( $cat_terms ) ) {
				$cats = implode( ', ', array_slice( wp_list_pluck( $cat_terms, 'name' ), 0, 4 ) );
			}
			$product = wc_get_product( $post_id );
			if ( $product ) {
				$price = html_entity_decode( wp_strip_all_tags( (string) wc_price( $product->get_price() ) ), ENT_QUOTES, 'UTF-8' );
				$stock = $product->is_in_stock();
			}
		} else {
			$cat_terms = get_the_terms( $post_id, 'category' );
			if ( $cat_terms && ! is_wp_error( $cat_terms ) ) {
				$cats = implode( ', ', array_slice( wp_list_pluck( $cat_terms, 'name' ), 0, 4 ) );
			}
		}

		$demand = class_exists( 'AIEO_SEO_Score' ) ? (int) AIEO_SEO_Score::demand_score( $type, $post_id ) : 0;

		return array(
			'type'         => ( 'product' === $type ) ? 'product' : $type,
			'site'         => get_bloginfo( 'name' ),
			'locale'       => get_locale(),
			'name'         => self::clean( get_the_title( $post ), 200 ),
			'brand'        => $brand,
			'categories'   => $cats,
			'price'        => $price,
			'in_stock'     => $stock,
			'demand'       => $demand,
			'demand_label' => $demand >= 66 ? 'best-seller' : ( $demand >= 33 ? 'steady seller' : 'low/long-tail' ),
			'excerpt'      => $excerpt,
			'cur_title'    => self::clean( (string) ( $row['title'] ?? '' ), 200 ),
			'cur_desc'     => self::clean( (string) ( $row['description'] ?? '' ), 300 ),
			'cur_kp'       => self::clean( (string) ( $row['focus_keyphrase'] ?? '' ), 100 ),
		);
	}

	
	
	

	
	private static function parse_json( $text ) {
		$text = trim( (string) $text );
		if ( '' === $text ) {
			return null;
		}
		
		$text = preg_replace( '/^```[a-z]*\s*|\s*```$/i', '', $text );
		$data = json_decode( $text, true );
		if ( is_array( $data ) ) {
			return $data;
		}
		
		if ( preg_match( '/\{.*\}/s', $text, $m ) ) {
			$data = json_decode( $m[0], true );
			if ( is_array( $data ) ) {
				return $data;
			}
		}
		return null;
	}

	private static function clean( $s, $max ) {
		$s = trim( preg_replace( '/\s+/u', ' ', wp_strip_all_tags( (string) $s ) ) );
		if ( function_exists( 'mb_substr' ) && mb_strlen( $s ) > $max ) {
			$s = mb_substr( $s, 0, $max );
		} elseif ( strlen( $s ) > $max ) {
			$s = substr( $s, 0, $max );
		}
		return $s;
	}
}
