<?php
/**
 * Sifency AI — Builder Item Generator
 *
 * @package Sifency_Addons
 * @since   1.0.5
 */

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

class Sifency_Addons_AI_Builder_Item_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 function generate( string $prompt ): array|\WP_Error {
		$slug = $this->derive_slug_from_words( $prompt, 3, '-' );

		$php_code = $this->api->chat(
			Sifency_Addons_AI_Prompt_Engine::builder_item_system(),
			Sifency_Addons_AI_Prompt_Engine::builder_item_user( $prompt, $slug ),
			4000
		);

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

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

		$meta = $this->writer->write( 'builder-items', $slug, $php_code );
		if ( is_wp_error( $meta ) ) {
			return $meta;
		}

		$meta['code_preview'] = mb_substr( $php_code, 0, 600 ) . "\n// … (truncated for preview)";
		return $meta;
	}

	private function validate( string $code ): bool|\WP_Error {
		if ( strlen( $code ) < 150 ) {
			return new \WP_Error( 'sifency_ai_too_short', __( 'The AI returned a response that is too short.', 'sifency-addons' ) );
		}

		$required_patterns = array(
			'/class\s+Sifency_Addons_AI_\w+_Builder_Item/' => 'Builder Item class declaration',
			'/function\s+render\s*\(\s*\)/'                => 'render() method',
		);

		foreach ( $required_patterns as $pattern => $label ) {
			if ( ! preg_match( $pattern, $code ) ) {
				return new \WP_Error(
					'sifency_ai_invalid',
					sprintf(
					/* translators: %s: name of the missing code element */
						__( 'Generated code is missing: %s', 'sifency-addons' ),
						$label
					)
				);
			}
		}

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