<?php
/**
 * Sifency AI — CPT Generator
 *
 * Orchestrates the full pipeline for Custom Post Type generation:
 *   1. Derive a clean slug from the user's prompt.
 *   2. Ask the AI API to produce a CPT registration 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_CPT_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 CPT class 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, 2, '_' );

		// --- Call AI -------------------------------------------------------
		$php_code = $this->api->chat(
			Sifency_Addons_AI_Prompt_Engine::cpt_system(),
			Sifency_Addons_AI_Prompt_Engine::cpt_user( $prompt, $slug ),
			4000
		);

		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( 'cpts', $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 CPT class.
	 */
	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 to be a valid CPT class. Please try again with a more detailed prompt.', 'sifency-addons' )
			);
		}

		$required_patterns = array(
			'/register_post_type\s*\(/'                 => 'register_post_type() call',
			'/class\s+Sifency_Addons_AI_\w+_CPT/'       => 'CPT class declaration',
			'/function\s+register_post_type\s*\(\s*\)/' => 'register_post_type() method',
		);

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

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