<?php
/**
 * Pro AI — automatic image alt text (BYOK, vision when available).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_ai_alt_enabled' ) ) {
	function newsai_ai_alt_enabled() {
		if ( ! function_exists( 'newsai_is_pro' ) || ! newsai_is_pro() ) {
			return false;
		}
		return get_option( 'newsai_ai_alt_enabled', 'no' ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_ai_alt_on_upload' ) ) {
	function newsai_ai_alt_on_upload() {
		return get_option( 'newsai_ai_alt_on_upload', 'yes' ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_ai_alt_attachment_context' ) ) {
	/**
	 * @return array{title:string,article_title:string,caption:string}
	 */
	function newsai_ai_alt_attachment_context( $attachment_id ) {
		$attachment_id = (int) $attachment_id;
		$post          = get_post( $attachment_id );
		$title         = $post ? (string) $post->post_title : '';
		$caption       = $post ? (string) $post->post_excerpt : '';
		$article_title = '';
		$parent_id     = (int) wp_get_post_parent_id( $attachment_id );
		if ( $parent_id > 0 ) {
			$article_title = (string) get_the_title( $parent_id );
		}
		return [
			'title'         => $title,
			'article_title' => $article_title,
			'caption'       => $caption,
		];
	}
}

if ( ! function_exists( 'newsai_ai_alt_generate_for_attachment' ) ) {
	/**
	 * @param int $attachment_id Attachment post ID.
	 * @param int $user_id       User to charge against daily quota (0 = skip quota check increment attribution only when >0).
	 * @return array{ok:bool,alt:string,error:string,remaining:int}
	 */
	function newsai_ai_alt_generate_for_attachment( $attachment_id, $user_id = 0, $force = false ) {
		$attachment_id = (int) $attachment_id;
		$out           = [
			'ok'        => false,
			'alt'       => '',
			'error'     => '',
			'remaining' => 0,
		];

		if ( $attachment_id < 1 || ! wp_attachment_is_image( $attachment_id ) ) {
			$out['error'] = __( 'Not a valid image attachment.', 'newsroom-ai-assistant' );
			return $out;
		}

		if ( ! $force ) {
			$existing = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
			if ( is_string( $existing ) && trim( $existing ) !== '' ) {
				$out['error'] = __( 'Alt text already set.', 'newsroom-ai-assistant' );
				return $out;
			}
		}

		if ( ! function_exists( 'newsai_ai_is_active' ) || ! newsai_ai_is_active() ) {
			$out['error'] = __( 'AI Assist is not configured.', 'newsroom-ai-assistant' );
			return $out;
		}

		if ( $user_id < 1 ) {
			$user_id = get_current_user_id();
		}
		if ( $user_id > 0 && function_exists( 'newsai_ai_rate_limit_remaining' ) && newsai_ai_rate_limit_remaining( $user_id ) <= 0 ) {
			$out['error']     = __( 'Daily AI limit reached for this user.', 'newsroom-ai-assistant' );
			$out['remaining'] = 0;
			return $out;
		}

		$ctx    = newsai_ai_alt_attachment_context( $attachment_id );
		$system = 'You write concise, factual image alt text for news publishers. '
			. 'Return strict JSON: {"alt":"..."} only. Alt must be 12–125 characters, no quotes inside, no HTML, no "image of". '
			. ( function_exists( 'newsai_ai_language_directive' ) ? newsai_ai_language_directive() : 'Write in the site language.' );

		$user = wp_json_encode(
			[
				'media_title'   => $ctx['title'],
				'article_title' => $ctx['article_title'],
				'caption'       => $ctx['caption'],
				'site_name'     => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
			]
		);

		$result = function_exists( 'newsai_ai_call_vision_json' )
			? newsai_ai_call_vision_json( $attachment_id, $system, (string) $user, 'alt_text|' . $attachment_id . '|' . md5( (string) $user ) )
			: [ 'ok' => false, 'data' => null, 'error' => 'Vision unavailable.', 'remaining' => 0 ];

		if ( empty( $result['ok'] ) || ! is_array( $result['data'] ) ) {
			$out['error']     = (string) ( $result['error'] ?? __( 'AI request failed.', 'newsroom-ai-assistant' ) );
			$out['remaining'] = (int) ( $result['remaining'] ?? 0 );
			return $out;
		}

		$alt = isset( $result['data']['alt'] ) ? sanitize_text_field( (string) $result['data']['alt'] ) : '';
		$alt = trim( preg_replace( '/\s+/u', ' ', $alt ) );
		if ( function_exists( 'mb_strlen' ) && mb_strlen( $alt, 'UTF-8' ) > 125 ) {
			$alt = trim( mb_substr( $alt, 0, 122, 'UTF-8' ) ) . '…';
		} elseif ( strlen( $alt ) > 125 ) {
			$alt = substr( $alt, 0, 122 ) . '…';
		}

		if ( $alt === '' || ( function_exists( 'mb_strlen' ) ? mb_strlen( $alt, 'UTF-8' ) : strlen( $alt ) ) < 10 ) {
			$out['error'] = __( 'AI returned alt text that was too short.', 'newsroom-ai-assistant' );
			return $out;
		}

		update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt );
		update_post_meta( $attachment_id, '_newsai_ai_alt_generated', time() );

		$out['ok']        = true;
		$out['alt']       = $alt;
		$out['remaining'] = (int) ( $result['remaining'] ?? ( function_exists( 'newsai_ai_rate_limit_remaining' ) ? newsai_ai_rate_limit_remaining( $user_id ) : 0 ) );
		return $out;
	}
}

if ( ! function_exists( 'newsai_ai_alt_schedule_for_attachment' ) ) {
	function newsai_ai_alt_schedule_for_attachment( $attachment_id ) {
		if ( ! newsai_ai_alt_enabled() || ! newsai_ai_alt_on_upload() ) {
			return;
		}
		$attachment_id = (int) $attachment_id;
		if ( $attachment_id < 1 || ! wp_attachment_is_image( $attachment_id ) ) {
			return;
		}
		if ( ! function_exists( 'newsai_ai_is_active' ) || ! newsai_ai_is_active() ) {
			return;
		}
		$existing = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
		if ( is_string( $existing ) && trim( $existing ) !== '' ) {
			return;
		}
		$user_id = get_current_user_id();
		if ( ! wp_next_scheduled( 'newsai_ai_alt_generate_event', [ $attachment_id, $user_id ] ) ) {
			wp_schedule_single_event( time() + 5, 'newsai_ai_alt_generate_event', [ $attachment_id, $user_id ] );
		}
	}
}
add_action( 'add_attachment', 'newsai_ai_alt_schedule_for_attachment', 30 );

if ( ! function_exists( 'newsai_ai_alt_run_scheduled' ) ) {
	function newsai_ai_alt_run_scheduled( $attachment_id, $user_id ) {
		newsai_ai_alt_generate_for_attachment( (int) $attachment_id, (int) $user_id );
	}
}
add_action( 'newsai_ai_alt_generate_event', 'newsai_ai_alt_run_scheduled', 10, 2 );

if ( ! function_exists( 'newsai_ai_ajax_generate_alt' ) ) {
	function newsai_ai_ajax_generate_alt() {
		if ( function_exists( 'newsai_ai_check_request' ) ) {
			newsai_ai_check_request();
		}
		$attachment_id = isset( $_POST['attachment_id'] ) ? (int) $_POST['attachment_id'] : 0;
		if ( $attachment_id < 1 || ! current_user_can( 'edit_post', $attachment_id ) ) {
			wp_send_json_error( [ 'message' => 'invalid_attachment' ], 400 );
		}
		$result = newsai_ai_alt_generate_for_attachment( $attachment_id, get_current_user_id(), true );
		if ( empty( $result['ok'] ) ) {
			wp_send_json_error(
				[
					'message'   => (string) ( $result['error'] ?? 'failed' ),
					'remaining' => (int) ( $result['remaining'] ?? 0 ),
				],
				400
			);
		}
		wp_send_json_success(
			[
				'alt'       => (string) $result['alt'],
				'remaining' => (int) $result['remaining'],
			]
		);
	}
}
add_action( 'wp_ajax_newsai_ai_generate_alt', 'newsai_ai_ajax_generate_alt' );

if ( ! function_exists( 'newsai_ai_alt_admin_assets' ) ) {
	function newsai_ai_alt_admin_assets( $hook ) {
		if ( ! newsai_ai_alt_enabled() || ! function_exists( 'newsai_ai_is_active' ) || ! newsai_ai_is_active() ) {
			return;
		}
		$allowed = [ 'upload.php', 'post.php', 'post-new.php', 'media.php', 'site-editor.php', 'widgets.php', 'edit.php' ];
		if ( ! in_array( $hook, $allowed, true ) ) {
			return;
		}

		$version = defined( 'NEWSAI_VERSION' ) ? NEWSAI_VERSION : '2.6.0';
		$script  = ( defined( 'NEWSAI_URL' ) ? NEWSAI_URL : plugin_dir_url( dirname( __DIR__ ) . '/newsroom-ai-assistant.php' ) ) . 'assets/newsai-ai-alt.js';

		wp_enqueue_script( 'newsai-ai-alt', $script, [ 'jquery' ], $version, true );
		wp_localize_script(
			'newsai-ai-alt',
			'newsaiAiAlt',
			[
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'newsai_ajax_nonce' ),
				'label'   => __( 'Generate alt (AI)', 'newsroom-ai-assistant' ),
				'busy'    => __( 'Generating…', 'newsroom-ai-assistant' ),
				'i18n'    => [
					'done'               => __( 'Alt text generated.', 'newsroom-ai-assistant' ),
					'generic'            => __( 'AI alt generation failed. Please try again.', 'newsroom-ai-assistant' ),
					'no_attachment'      => __( 'No image selected. Open the image (or its details) and click again.', 'newsroom-ai-assistant' ),
					'invalid_attachment' => __( 'Could not detect the image. Open the image details and try again.', 'newsroom-ai-assistant' ),
					'unauthorized'       => __( 'You do not have permission to edit this image.', 'newsroom-ai-assistant' ),
					'pro_required'       => __( 'A Pro license is required for AI alt text.', 'newsroom-ai-assistant' ),
					'ai_not_configured'  => __( 'AI Assist is not configured. Add a provider and API key in Settings → AI.', 'newsroom-ai-assistant' ),
				],
			]
		);
	}
}
add_action( 'admin_enqueue_scripts', 'newsai_ai_alt_admin_assets' );
