<?php
/**
 * Metadata-based alt text suggestions (no API).
 *
 * @package AIAltTextGenerator
 * @since 1.4.0
 */

namespace AIAltTextGenerator;

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

/**
 * Local suggestion engine using filename/title/caption.
 *
 * @since 1.4.0
 */
class LocalSuggester {

	/**
	 * Suggest alt text from attachment metadata.
	 */
	public static function suggest( int $attachment_id ): string {
		$post = get_post( $attachment_id );
		if ( ! $post instanceof \WP_Post ) {
			return '';
		}

		$candidates = [];

		$title = trim( (string) $post->post_title );
		if ( $title !== '' && ! self::isGenericTitle( $title ) ) {
			$candidates[] = $title;
		}

		$caption = trim( (string) $post->post_excerpt );
		if ( $caption !== '' ) {
			$candidates[] = $caption;
		}

		$description = trim( wp_strip_all_tags( (string) $post->post_content ) );
		if ( $description !== '' ) {
			$candidates[] = $description;
		}

		$filename = self::humanizeFilename( (string) get_attached_file( $attachment_id ) );
		if ( $filename !== '' ) {
			$candidates[] = $filename;
		}

		$ctx = ContextHelper::getContext( $attachment_id );
		if ( $ctx['product_title'] !== '' ) {
			array_unshift( $candidates, $ctx['product_title'] );
		}

		$suggestion = '';
		foreach ( $candidates as $candidate ) {
			$candidate = trim( preg_replace( '/\s+/', ' ', $candidate ) ?? '' );
			if ( $candidate !== '' && ! QualityScorer::isWeak( $candidate ) ) {
				$suggestion = $candidate;
				break;
			}
		}

		if ( $suggestion === '' && $filename !== '' ) {
			$suggestion = $filename;
		}

		/**
		 * Filter local (non-AI) alt text suggestion.
		 *
		 * @param string $suggestion    Suggested alt text.
		 * @param int    $attachment_id Attachment ID.
		 */
		return (string) apply_filters( 'wpps_ai_alt_text_local_suggestion', $suggestion, $attachment_id );
	}

	private static function isGenericTitle( string $title ): bool {
		return in_array( strtolower( $title ), [ 'untitled', 'image', 'photo' ], true );
	}

	private static function humanizeFilename( string $path ): string {
		$base = pathinfo( $path, PATHINFO_FILENAME );
		$base = preg_replace( '/[-_]+/', ' ', (string) $base ) ?? '';
		$base = preg_replace( '/\b\d{3,}\b/', '', $base ) ?? '';
		$base = trim( preg_replace( '/\s+/', ' ', $base ) ?? '' );

		if ( $base === '' ) {
			return '';
		}

		return ucwords( strtolower( $base ) );
	}
}
