<?php
/**
 * SEO Agent Chat Functionality
 *
 * Provides a global AI chat interface on the ClearPost dashboard page.
 * Users can ask questions about their SEO pipeline (keywords, calendar, posts, etc.)
 * and get AI-powered responses with tool-use capabilities.
 *
 * @package Simple_Ai_Auto_Post
 * @since 2.1.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

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

/**
 * Get the license key (paid or trial).
 *
 * @return string The license key or empty string.
 */
function saiap_seo_agent_get_license_key() {
	$license_key = get_option( 'saiap_license_key', '' );
	if ( empty( $license_key ) ) {
		$license_key = get_option( 'saiap_trial_license_key', '' );
	}
	return $license_key;
}

/**
 * Enqueue SEO Agent Chat assets on the ClearPost dashboard page.
 *
 * @param string $hook The current admin page hook.
 */
function saiap_enqueue_seo_agent_chat( $hook ) {
	// Only load on the ClearPost dashboard page.
	if ( 'toplevel_page_saiap' !== $hook ) {
		return;
	}

	// Only load for premium users (paid or trial).
	$license_key = saiap_seo_agent_get_license_key();
	if ( empty( $license_key ) ) {
		return;
	}

	$plugin_dir = plugin_dir_path( dirname( __FILE__ ) );
	$plugin_url = plugin_dir_url( dirname( __FILE__ ) );

	$bundle_path = $plugin_dir . 'assets/js/dist/seo-agent-chat.bundle.js';
	$css_path    = $plugin_dir . 'assets/css/seo-agent-chat.css';

	// Enqueue CSS.
	if ( file_exists( $css_path ) ) {
		wp_enqueue_style(
			'saiap-seo-agent-chat',
			$plugin_url . 'assets/css/seo-agent-chat.css',
			array( 'saiap-design-system' ),
			filemtime( $css_path )
		);
	}

	// Enqueue React bundle.
	if ( file_exists( $bundle_path ) ) {
		wp_enqueue_script(
			'saiap-seo-agent-chat',
			$plugin_url . 'assets/js/dist/seo-agent-chat.bundle.js',
			array( 'wp-element', 'jquery' ),
			filemtime( $bundle_path ),
			true
		);

		wp_localize_script(
			'saiap-seo-agent-chat',
			'saiapSeoAgentChat',
			array(
				'ajaxurl'         => admin_url( 'admin-ajax.php' ),
				'nonce'           => wp_create_nonce( 'saiap_seo_agent_chat' ),
				'domain'          => saiap_get_server_host(),
				// Hide the FAB entirely while setup is in progress so the
				// streaming narration view is the only chat surface.
				// (FEAT-ChatDrivenSetup)
				'hidden'          => function_exists( 'saiap_is_setup_in_progress' ) && saiap_is_setup_in_progress(),
				'currentProvider' => get_option( 'saiap_default_provider', 'anthropic' ),
				'currentModel'    => saiap_get_model_for_provider( get_option( 'saiap_default_provider', 'anthropic' ) ),
				'availableModels' => saiap_get_ai_models(),
				'i18n'            => array(
					'title'       => __( 'Clarence', 'clearpost-simple-ai-auto-post' ),
					'subtitle'    => __( 'AI Agent', 'clearpost-simple-ai-auto-post' ),
					'placeholder' => __( 'Ask about your keywords, calendar, rankings...', 'clearpost-simple-ai-auto-post' ),
					'send'        => __( 'Send', 'clearpost-simple-ai-auto-post' ),
					'thinking'    => __( 'Thinking...', 'clearpost-simple-ai-auto-post' ),
					'error'       => __( 'Something went wrong. Please try again.', 'clearpost-simple-ai-auto-post' ),
					'welcome'     => __( "Hey! I'm Clarence, your SEO agent. Here's what I can do:\n\n**Research & insights**\n- Look up search volume, difficulty, and CPC for any keyword\n- Search the web for competitor research\n- Find images on Unsplash for your posts\n\n**Monitor your SEO**\n- Review your keywords, posts, and content calendar\n- Check your rank tracking positions and trends\n- View your autopilot and scheduling settings\n\n**Take action**\n- Add new keywords (with metrics lookup first)\n- Archive or reactivate keywords in bulk\n- Reschedule, skip, or update calendar items\n- Toggle daily rank tracking for keywords\n- Update autopilot settings (on/off, posts per week, review mode)\n\nWhat would you like to do?", 'clearpost-simple-ai-auto-post' ),
				),
			)
		);
	}
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_seo_agent_chat' );

/**
 * Render the chat mount point on the dashboard page.
 * Called from dashboard.php render function.
 */
function saiap_render_seo_agent_chat_mount() {
	$license_key = saiap_seo_agent_get_license_key();
	if ( empty( $license_key ) ) {
		return;
	}
	echo '<div id="saiap-seo-agent-chat-root"></div>';
}

/**
 * AJAX handler: Start a new SEO agent chat message.
 * Proxies to the premium backend POST /api/seo-agent/chat.
 */
function saiap_ajax_seo_agent_chat_send() {
	check_ajax_referer( 'saiap_seo_agent_chat', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
	}

	$messages            = isset( $_POST['messages'] ) ? json_decode( wp_unslash( $_POST['messages'] ), true ) : array();
	$provider            = isset( $_POST['provider'] ) ? sanitize_text_field( wp_unslash( $_POST['provider'] ) ) : '';
	$model               = isset( $_POST['model'] ) ? sanitize_text_field( wp_unslash( $_POST['model'] ) ) : '';
	$compaction_summary  = isset( $_POST['compaction_summary'] ) ? sanitize_textarea_field( wp_unslash( $_POST['compaction_summary'] ) ) : '';

	if ( empty( $messages ) || ! is_array( $messages ) ) {
		wp_send_json_error( array( 'message' => 'No messages provided' ) );
	}

	// Sanitize messages.
	$sanitized_messages = array();
	foreach ( $messages as $msg ) {
		if ( ! isset( $msg['role'] ) || ! isset( $msg['content'] ) ) {
			continue;
		}
		$sanitized_messages[] = array(
			'role'    => sanitize_text_field( $msg['role'] ),
			'content' => sanitize_textarea_field( $msg['content'] ),
		);
	}

	$license_key = saiap_seo_agent_get_license_key();
	$domain      = saiap_get_server_host();

	$body = array(
		'license_key' => $license_key,
		'domain'      => $domain,
		'messages'    => $sanitized_messages,
	);

	if ( ! empty( $provider ) ) {
		$body['provider'] = $provider;
	}
	if ( ! empty( $model ) ) {
		$body['model'] = $model;
	}
	if ( ! empty( $compaction_summary ) ) {
		$body['compaction_summary'] = $compaction_summary;
	}

	$response = wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/seo-agent/chat',
		array(
			'timeout' => 30,
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode( $body ),
		)
	);

	if ( is_wp_error( $response ) ) {
		wp_send_json_error( array( 'message' => 'Failed to connect to server: ' . $response->get_error_message() ) );
	}

	$status_code = wp_remote_retrieve_response_code( $response );
	$body_raw    = wp_remote_retrieve_body( $response );
	$data        = json_decode( $body_raw, true );

	if ( 202 === $status_code && ! empty( $data['job_id'] ) ) {
		wp_send_json_success( array( 'job_id' => sanitize_text_field( $data['job_id'] ) ) );
	} else {
		$error_msg = ! empty( $data['error'] ) ? $data['error'] : 'Unexpected response from server';
		wp_send_json_error( array( 'message' => $error_msg ), $status_code );
	}
}
add_action( 'wp_ajax_saiap_seo_agent_chat_send', 'saiap_ajax_seo_agent_chat_send' );

/**
 * AJAX handler: Poll for SEO agent chat job status.
 * Proxies to the premium backend GET /api/seo-agent/chat/:jobId.
 */
function saiap_ajax_seo_agent_chat_status() {
	check_ajax_referer( 'saiap_seo_agent_chat', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
	}

	$job_id = isset( $_POST['job_id'] ) ? sanitize_text_field( wp_unslash( $_POST['job_id'] ) ) : '';
	if ( empty( $job_id ) ) {
		wp_send_json_error( array( 'message' => 'No job_id provided' ) );
	}

	$response = wp_remote_get(
		SAIAP_PREMIUM_API_URL . '/api/seo-agent/chat/' . rawurlencode( $job_id ),
		array(
			'timeout' => 15,
			'headers' => array( 'Content-Type' => 'application/json' ),
		)
	);

	if ( is_wp_error( $response ) ) {
		wp_send_json_error( array( 'message' => 'Failed to check status: ' . $response->get_error_message() ) );
	}

	$body = json_decode( wp_remote_retrieve_body( $response ), true );

	if ( ! is_array( $body ) || ! isset( $body['status'] ) ) {
		wp_send_json_error( array( 'message' => 'Invalid response from server' ) );
	}

	wp_send_json_success( $body );
}
add_action( 'wp_ajax_saiap_seo_agent_chat_status', 'saiap_ajax_seo_agent_chat_status' );
