<?php
/**
 * Image ALT context analyzer.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Chooses generation strategy based on available image context.
 */
class SmartyPress_AI_Image_ALT_Context_Analyzer {

	/**
	 * Analyze generation context and return strategy metadata.
	 *
	 * @param array $context  Attachment and SEO context.
	 * @param array $settings Module settings.
	 * @return array
	 */
	public function analyze( array $context, array $settings ) {
		if ( 'context' !== ( $settings['vision_mode'] ?? 'vision' ) ) {
			return $this->result( 'vision_two_step', 'high', false, array( 'vision_mode_enabled' ) );
		}

		$reasons          = array();
		$has_post         = is_array( $context['primary_post'] ?? null );
		$has_keywords     = ! empty( $context['focus_keywords'] );
		$has_title        = $this->is_useful_text( $context['attachment_title'] ?? '' );
		$has_filename     = $this->is_useful_filename( $context['filename'] ?? '' );
		$has_existing_alt = $this->is_useful_text( $context['current_alt'] ?? '' );
		$has_caption      = $this->is_useful_text( $context['current_caption'] ?? '' );

		if ( $has_post ) {
			$reasons[] = 'related_post_found';
		}

		if ( $has_keywords ) {
			$reasons[] = 'seo_keyword_found';
		}

		if ( $has_title ) {
			$reasons[] = 'useful_attachment_title';
		}

		if ( $has_filename ) {
			$reasons[] = 'useful_filename';
		}

		if ( $has_existing_alt || $has_caption ) {
			$reasons[] = 'existing_metadata_found';
		}

		if ( $has_post && $has_keywords ) {
			return $this->result( 'context_post_keyword', 'good', false, $reasons );
		}

		if ( $has_post ) {
			return $this->result( 'context_post', 'medium', false, $reasons );
		}

		if ( $has_title || $has_filename || $has_existing_alt || $has_caption ) {
			return $this->result( 'context_existing_metadata', 'low', false, $reasons );
		}

		$reasons[] = 'poor_context';

		return $this->result( 'poor_custom_prompt', 'low', true, $reasons );
	}

	/**
	 * Build result.
	 *
	 * @param string $strategy     Strategy key.
	 * @param string $confidence   Confidence key.
	 * @param bool   $needs_review Whether user review is recommended.
	 * @param array  $reasons      Machine-readable reasons.
	 * @return array
	 */
	private function result( $strategy, $confidence, $needs_review, array $reasons ) {
		return array(
			'strategy'     => $strategy,
			'confidence'   => $confidence,
			'needs_review' => (bool) $needs_review,
			'reasons'      => array_values( array_unique( $reasons ) ),
		);
	}

	/**
	 * Check whether text is useful enough for context-only generation.
	 *
	 * @param string $text Text.
	 * @return bool
	 */
	private function is_useful_text( $text ) {
		$text = trim( wp_strip_all_tags( (string) $text ) );

		if ( mb_strlen( $text, 'UTF-8' ) < 4 ) {
			return false;
		}

		return ! $this->is_generic_token( $text );
	}

	/**
	 * Check whether filename contains useful human-readable context.
	 *
	 * @param string $filename Clean filename without extension.
	 * @return bool
	 */
	private function is_useful_filename( $filename ) {
		$filename = trim( (string) $filename );

		if ( ! $this->is_useful_text( $filename ) ) {
			return false;
		}

		if ( preg_match( '/^(img|dsc|pxl|screenshot|screen shot|image|photo|picture|whatsapp image)(\\s+|\\-|_)?[\\d\\w\\-\\s]*$/i', $filename ) ) {
			return false;
		}

		if ( preg_match( '/^[a-f0-9]{8,}$/i', str_replace( array( '-', '_' ), '', $filename ) ) ) {
			return false;
		}

		if ( preg_match( '/^\\d+$/', str_replace( ' ', '', $filename ) ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Detect generic single-token context values.
	 *
	 * @param string $text Text.
	 * @return bool
	 */
	private function is_generic_token( $text ) {
		$normalized = strtolower( trim( preg_replace( '/\\s+/u', ' ', $text ) ) );
		$generic    = array(
			'image',
			'photo',
			'picture',
			'img',
			'screenshot',
			'screen shot',
			'untitled',
			'attachment',
			'file',
			'logo',
			'new image',
		);

		return in_array( $normalized, $generic, true );
	}
}
