<?php
/**
 * Trial Setup Stream
 *
 * During automated setup (5–10 min Opus strategy session), replace the static
 * spinner with a live narration view driven by an SSE stream from the
 * premium backend. The model's tokens stream in, tool calls render as cards,
 * and the user confirms the plan before the first post is generated.
 *
 * Part of FEAT-ChatDrivenSetup.
 *
 * @package Simple_Ai_Auto_Post
 * @since 2.8.0
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Return the license or trial key for this install, mirroring the SEO agent
 * chat helper so both modules stay aligned.
 */
function saiap_setup_stream_get_license_key() {
	$key = get_option( 'saiap_license_key', '' );
	if ( empty( $key ) ) {
		$key = get_option( 'saiap_trial_license_key', '' );
	}
	return $key;
}

/**
 * Enqueue setup stream assets on the ClearPost dashboard page.
 *
 * Only enqueues when a trial/license is present AND setup is in progress —
 * there's no need to ship this bundle for post-setup sessions.
 *
 * @param string $hook The current admin page hook.
 */
function saiap_enqueue_setup_stream( $hook ) {
	if ( 'toplevel_page_saiap' !== $hook ) {
		return;
	}

	if ( ! saiap_is_setup_in_progress() ) {
		return;
	}

	$license_key = saiap_setup_stream_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/setup-stream.bundle.js';
	$css_path    = $plugin_dir . 'assets/css/setup-stream.css';

	if ( file_exists( $css_path ) ) {
		wp_enqueue_style(
			'saiap-setup-stream',
			$plugin_url . 'assets/css/setup-stream.css',
			array( 'saiap-design-system' ),
			filemtime( $css_path )
		);
	}

	if ( ! file_exists( $bundle_path ) ) {
		return;
	}

	wp_enqueue_script(
		'saiap-setup-stream',
		$plugin_url . 'assets/js/dist/setup-stream.bundle.js',
		array( 'wp-element', 'jquery' ),
		filemtime( $bundle_path ),
		true
	);

	// Browser-facing URLs need localhost, not host.docker.internal (which only resolves inside Docker).
	$browser_api_base = defined( 'SAIAP_PREMIUM_API_URL' )
		? str_replace( 'host.docker.internal', 'localhost', SAIAP_PREMIUM_API_URL )
		: '';

	wp_localize_script(
		'saiap-setup-stream',
		'saiapSetupStream',
		array(
			'ajaxurl'     => admin_url( 'admin-ajax.php' ),
			'nonce'       => wp_create_nonce( 'saiap_setup_stream' ),
			'apiBase'     => $browser_api_base,
			'domain'      => saiap_get_server_host(),
			'i18n'        => array(
				'preparing'    => __( 'Getting started...', 'clearpost-simple-ai-auto-post' ),
				'connecting'   => __( 'Tuning in...', 'clearpost-simple-ai-auto-post' ),
				'disconnected' => __( 'Lost the connection — reconnecting...', 'clearpost-simple-ai-auto-post' ),
				'failed'       => __( "Something went wrong. I've emailed the team — please try again in a few.", 'clearpost-simple-ai-auto-post' ),
				'done'         => __( "All set — opening your dashboard...", 'clearpost-simple-ai-auto-post' ),
				'answerSent'   => __( "Got it! Writing your first post right now...", 'clearpost-simple-ai-auto-post' ),
				'answerFailed' => __( "Couldn't send your answer — please try again.", 'clearpost-simple-ai-auto-post' ),
			),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'saiap_enqueue_setup_stream' );

/**
 * Render the mount point for the streaming narration UI.
 * Called by dashboard.php in place of the calendar grid while setup runs.
 */
function saiap_render_setup_stream_mount() {
	$license_key = saiap_setup_stream_get_license_key();
	if ( empty( $license_key ) ) {
		return;
	}
	echo '<div id="saiap-setup-stream-root" class="saiap-setup-stream-root"></div>';
}

/**
 * AJAX: Issue a stream token so the browser can open the SSE connection
 * and call the answer endpoint. Short-lived (5 min) per /api/trial/setup/token.
 */
function saiap_ajax_setup_stream_token() {
	check_ajax_referer( 'saiap_setup_stream', 'nonce' );

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

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

	if ( empty( $license_key ) || empty( $domain ) ) {
		wp_send_json_error( array( 'message' => 'Missing license or domain' ), 400 );
	}

	$response = wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/trial/setup/token',
		array(
			'timeout' => 10,
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode(
				array(
					'license_key' => $license_key,
					'domain'      => $domain,
				)
			),
		)
	);

	if ( is_wp_error( $response ) ) {
		wp_send_json_error( array( 'message' => 'Token issue failed: ' . $response->get_error_message() ) );
	}

	$body = json_decode( wp_remote_retrieve_body( $response ), true );
	if ( empty( $body['token'] ) ) {
		$error_msg = ! empty( $body['error'] ) ? $body['error'] : 'Token issue failed';
		wp_send_json_error( array( 'message' => $error_msg ), wp_remote_retrieve_response_code( $response ) );
	}

	wp_send_json_success(
		array(
			'token'     => $body['token'],
			'expiresIn' => isset( $body['expiresIn'] ) ? (int) $body['expiresIn'] : 300,
			'apiBase'   => str_replace( 'host.docker.internal', 'localhost', SAIAP_PREMIUM_API_URL ),
			'domain'    => $domain,
		)
	);
}
add_action( 'wp_ajax_saiap_setup_stream_token', 'saiap_ajax_setup_stream_token' );

/**
 * AJAX: Submit the user's answer to the pending confirmation question.
 * Proxies to POST /api/trial/setup/answer on the backend.
 */
function saiap_ajax_setup_stream_answer() {
	check_ajax_referer( 'saiap_setup_stream', 'nonce' );

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

	$token  = isset( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : '';
	$answer = isset( $_POST['answer'] ) ? sanitize_textarea_field( wp_unslash( $_POST['answer'] ) ) : '';
	$domain = saiap_get_server_host();

	if ( empty( $token ) || '' === $answer ) {
		wp_send_json_error( array( 'message' => 'Missing token or answer' ), 400 );
	}

	$response = wp_remote_post(
		SAIAP_PREMIUM_API_URL . '/api/trial/setup/answer',
		array(
			'timeout' => 10,
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode(
				array(
					'domain' => $domain,
					'token'  => $token,
					'answer' => $answer,
				)
			),
		)
	);

	if ( is_wp_error( $response ) ) {
		wp_send_json_error( array( 'message' => 'Answer submit failed: ' . $response->get_error_message() ) );
	}

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

	if ( 200 !== $status ) {
		$error_msg = ! empty( $body['error'] ) ? $body['error'] : 'Answer submit failed';
		wp_send_json_error( array( 'message' => $error_msg ), $status );
	}

	wp_send_json_success( $body );
}
add_action( 'wp_ajax_saiap_setup_stream_answer', 'saiap_ajax_setup_stream_answer' );
