<?php
/**
 * Sifency AI — Widget Generator
 *
 * Orchestrates the full pipeline:
 *   1. Derive a clean slug from the user's prompt.
 *   2. Ask the AI API to produce an Elementor widget class.
 *   3. Validate the returned PHP (light sanity check).
 *   4. Write the file via the File Writer.
 *   5. Return metadata so the admin UI can display the result.
 *
 * @package Sifency_Addons
 * @since   1.0.5
 */

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

class Sifency_Addons_AI_Widget_Generator {
	use Sifency_Addons_AI_Generator_Trait;

	private Sifency_Addons_AI_API $api;
	private Sifency_Addons_AI_File_Writer $writer;

	public function __construct() {
		$this->api    = new Sifency_Addons_AI_API();
		$this->writer = new Sifency_Addons_AI_File_Writer();
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  Public Entry Point                                                  */
	/* ------------------------------------------------------------------ */

	/**
	 * Generate a widget from a user prompt.
	 *
	 * @param  string $prompt  Natural language description.
	 * @return array|\WP_Error Metadata array on success, WP_Error on failure.
	 */
	public function generate( string $prompt ): array|\WP_Error {
		$slug = $this->derive_slug_from_words( $prompt, 4, '-' );

		// --- Call AI -------------------------------------------------------
		$php_code = $this->api->chat(
			Sifency_Addons_AI_Prompt_Engine::widget_system(),
			Sifency_Addons_AI_Prompt_Engine::widget_user( $prompt, $slug ),
			8000
		);

		if ( is_wp_error( $php_code ) ) {
			return $php_code;
		}

		// --- Clean & validate ----------------------------------------------
		$php_code = $this->clean_code( $php_code );

		$validation = $this->validate( $php_code );
		if ( is_wp_error( $validation ) ) {
			return $validation;
		}

		// --- Write file ----------------------------------------------------
		$meta = $this->writer->write( 'widgets', $slug, $php_code );
		if ( is_wp_error( $meta ) ) {
			return $meta;
		}

		// Attach a preview of the code for the UI
		$meta['code_preview'] = mb_substr( $php_code, 0, 600 ) . "\n// … (truncated for preview)";

		return $meta;
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  Validation                                                          */
	/* ------------------------------------------------------------------ */

	/**
	 * Light sanity check: ensure the returned code looks like a valid
	 * Elementor widget class before writing it to disk.
	 */
	private function validate( string $code ): bool|\WP_Error {
		if ( strlen( $code ) < 200 ) {
			return new \WP_Error(
				'sifency_ai_too_short',
				__( 'The AI returned a response that is too short to be a valid widget. Please try again with a more detailed prompt.', 'sifency-addons' )
			);
		}

		$required_patterns = array(
			'/class\s+Sifency_Addons_AI_\w+_Widget\s+extends\s+\\\\?Elementor\\\\Widget_Base/' => 'Widget class declaration',
			'/function\s+get_name\s*\(\s*\)/' => 'get_name()',
			'/function\s+render\s*\(\s*\)/'   => 'render()',
		);

		foreach ( $required_patterns as $pattern => $label ) {
			if ( ! preg_match( $pattern, $code ) ) {
				return new \WP_Error(
					'sifency_ai_invalid_widget',
					sprintf(
						/* translators: %s: name of the missing required method */
						__( 'Generated code is missing required method: %s. Please try a different prompt or be more specific.', 'sifency-addons' ),
						$label
					)
				);
			}
		}

		return $this->syntax_check( $code );
	}
}
