<?php
/**
 * Sifency AI — Shared Generator Trait
 *
 * Provides shared utilities for code cleaning, slug derivation,
 * and syntax checking across all generator types.
 *
 * @package Sifency_Addons
 * @since   1.0.5
 */

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

trait Sifency_Addons_AI_Generator_Trait {

	/**
	 * Clean markdown fences, stray <?php tags, and duplicate ABSPATH checks from AI output.
	 *
	 * @param  string $code Raw AI output.
	 * @return string Cleaned PHP code.
	 */
	protected function clean_code( string $code ): string {
		// Remove ```php ... ``` or ``` ... ``` fences.
		$code = preg_replace( '/^```(?:php)?\s*/i', '', trim( $code ) );
		$code = preg_replace( '/\s*```\s*$/', '', $code );

		// Remove leading <?php if added.
		$code = preg_replace( '/^<\?php\s*/i', '', ltrim( $code ) );

		// Remove duplicate ABSPATH checks.
		$code = preg_replace(
			'/if\s*\(\s*!\s*defined\s*\(\s*[\'"]ABSPATH[\'"]\s*\)\s*\)\s*\{?\s*exit\s*[;(][^}]*\}?\s*/i',
			'',
			$code
		);

		return trim( $code );
	}

	/**
	 * Derive a clean slug from user prompt by extracting meaningful keywords.
	 *
	 * @param  string $prompt    Natural language prompt.
	 * @param  int    $max_words Max number of words to extract.
	 * @param  string $separator Word join character.
	 * @return string Cleaned slug.
	 */
	protected function derive_slug_from_words( string $prompt, int $max_words = 3, string $separator = '-' ): string {
		$stop_words = array(
			'a',
			'an',
			'the',
			'and',
			'or',
			'but',
			'with',
			'for',
			'to',
			'in',
			'on',
			'at',
			'of',
			'by',
			'from',
			'that',
			'is',
			'it',
			'create',
			'make',
			'build',
			'generate',
			'add',
			'new',
			'custom',
			'post',
			'type',
			'cpt',
			'meta',
			'box',
			'metabox',
			'theme',
			'builder',
			'item',
			'widget',
			'slider',
			'pagination',
			'navigation',
		);

		$words = preg_split( '/\s+/', strtolower( trim( $prompt ) ) );
		$words = array_filter( $words, fn( $w ) => ! in_array( $w, $stop_words, true ) );
		$words = array_values( $words );

		$slug_words = array_slice( $words, 0, $max_words );
		$slug_parts = array_map( fn( $w ) => preg_replace( '/[^a-z0-9]/', '', $w ), $slug_words );
		$slug_parts = array_filter( $slug_parts );

		return implode( $separator, $slug_parts );
	}

	/**
	 * Verify PHP code syntax without executing it.
	 *
	 * @param  string $code PHP code to check.
	 * @return bool|\WP_Error True on success, WP_Error on syntax issue.
	 */
	protected function syntax_check( string $code ): bool|\WP_Error {
		try {
			token_get_all( '<?php ' . $code );
		} catch ( \ParseError $e ) {
			return new \WP_Error(
				'sifency_ai_syntax',
				sprintf(
					/* translators: %s: PHP parse error message */
					__( 'Generated PHP has a syntax error: %s', 'sifency-addons' ),
					$e->getMessage()
				)
			);
		}
		return true;
	}
}
