<?php
namespace WPLens\Schema\Generators;

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

final class HowtoGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'howto'; }
	public function get_label(): string { return __( 'HowTo (auto-detected from ordered steps)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		if ( ! $post instanceof \WP_Post ) { return false; }
		return in_array( $post->post_type, array( 'post', 'page' ), true );
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		if ( ! $post ) { return null; }

		$steps = $this->extract_step_headings( (string) $post->post_content );
		if ( count( $steps ) < 3 ) {
			$steps = $this->extract_ordered_list( (string) $post->post_content );
		}
		if ( count( $steps ) < 3 ) {
			return null;
		}

		$list = array();
		foreach ( $steps as $i => $step ) {
			$list[] = array(
				'@type'    => 'HowToStep',
				'position' => $i + 1,
				'name'     => $step['name'],
				'text'     => $step['text'],
			);
		}

		return array(
			'@type'       => 'HowTo',
			'@id'         => get_permalink( $post ) . '#howto',
			'name'        => wp_strip_all_tags( get_the_title( $post ) ),
			'step'        => $list,
			'totalTime'   => 'PT' . max( 5, count( $list ) * 5 ) . 'M', // rough estimate
		);
	}

	/**
	 * @return array<int, array{name:string, text:string}>
	 */
	private function extract_step_headings( string $content ): array {
		$steps = array();
		if ( preg_match_all(
			'#<h[2-4]\b[^>]*>\s*(?:Step\s+\d+[:.\s]*)\s*(?P<name>[^<]+)</h[2-4]>(?P<text>.*?)(?=<h[2-4]\b|$)#is',
			$content,
			$m,
			PREG_SET_ORDER
		) ) {
			foreach ( $m as $row ) {
				$name = trim( wp_strip_all_tags( $row['name'] ) );
				$text = trim( wp_strip_all_tags( $row['text'] ) );
				if ( '' !== $name && '' !== $text ) {
					$steps[] = array( 'name' => $name, 'text' => preg_replace( '/\s+/u', ' ', $text ) );
				}
			}
		}
		return $steps;
	}

	/**
	 * @return array<int, array{name:string, text:string}>
	 */
	private function extract_ordered_list( string $content ): array {
		$steps = array();
		if ( preg_match( '#<ol\b[^>]*>(?P<items>.*?)</ol>#is', $content, $ol ) ) {
			if ( preg_match_all( '#<li\b[^>]*>(?P<item>.*?)</li>#is', $ol['items'], $m, PREG_SET_ORDER ) ) {
				foreach ( $m as $row ) {
					$text = trim( wp_strip_all_tags( $row['item'] ) );
					if ( '' === $text ) { continue; }
					$text = preg_replace( '/\s+/u', ' ', $text );
					$name = wp_trim_words( $text, 6, '…' );
					$steps[] = array( 'name' => $name, 'text' => $text );
				}
			}
		}
		return $steps;
	}
}
