<?php
namespace WPLens\Schema\Generators;

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

final class VideoGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'video'; }
	public function get_label(): string { return __( 'VideoObject (embedded YouTube / Vimeo)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		if ( ! $post instanceof \WP_Post ) { return false; }
		return (bool) $this->extract_video_urls( (string) $post->post_content );
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		if ( ! $post ) { return null; }
		$urls = $this->extract_video_urls( (string) $post->post_content );
		if ( empty( $urls ) ) { return null; }

		// Emit a VideoObject for the first detected video — Google's rich-result eligibility is per-video.
		$url   = $urls[0];
		$title = wp_strip_all_tags( get_the_title( $post ) );

		return array(
			'@type'        => 'VideoObject',
			'@id'          => get_permalink( $post ) . '#video',
			'name'         => $title,
			'description'  => wp_strip_all_tags( wp_trim_words( (string) $post->post_content, 30, '' ) ),
			'embedUrl'     => $url,
			'uploadDate'   => mysql2date( 'c', $post->post_date_gmt, false ) ?: '',
			'thumbnailUrl' => $this->thumbnail_for( $url ),
		);
	}

	/**
	 * @return array<int, string>
	 */
	private function extract_video_urls( string $content ): array {
		$found = array();
		// YouTube embeds / oEmbed / share URLs
		if ( preg_match_all( '#https?://(?:www\.)?(?:youtube\.com/(?:watch\?v=|embed/|v/)|youtu\.be/)([A-Za-z0-9_-]{6,})#i', $content, $m ) ) {
			foreach ( $m[1] as $id ) {
				$found[] = 'https://www.youtube.com/embed/' . $id;
			}
		}
		// Vimeo
		if ( preg_match_all( '#https?://(?:www\.)?(?:player\.)?vimeo\.com/(?:video/)?(\d+)#i', $content, $m ) ) {
			foreach ( $m[1] as $id ) {
				$found[] = 'https://player.vimeo.com/video/' . $id;
			}
		}
		return array_values( array_unique( $found ) );
	}

	private function thumbnail_for( string $url ): string {
		if ( preg_match( '#youtube\.com/embed/([A-Za-z0-9_-]+)#', $url, $m ) ) {
			return 'https://i.ytimg.com/vi/' . $m[1] . '/hqdefault.jpg';
		}
		return '';
	}
}
