<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * VMO Media Integration Specialist AI Agent
 * Handles creative media integration through natural language prompts
 */

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

class VMO_Media_Integration_Agent {
    
    private $api_key;
    private $agent_system_prompt;
    
    public function __construct() {
        $this->api_key = get_option('vmo_openai_api_key');
        $this->init_agent_system_prompt();
        $this->init_hooks();
    }
    
    private function prepare_long_running_runtime() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }
        if (function_exists('ignore_user_abort')) {
            @ignore_user_abort(true);
        }
        if (function_exists('ini_set')) {
            @ini_set('memory_limit', '512M');
        }
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        add_action('wp_ajax_vmo_integrate_media', array($this, 'handle_media_integration'));
    }
    
    /**
     * Initialize the specialized system prompt for the Media Integration Agent
     */
    private function init_agent_system_prompt() {
        $this->agent_system_prompt = "You are the Media Integration Specialist, a senior AI agent with 20+ years of experience in creative web design, visual composition, and responsive media placement.

Your role is to interpret natural language requests for media integration and generate precise CSS and HTML code that creatively integrates media (images, videos, graphics) into existing web projects.

CAPABILITIES:
- Intelligent media placement within complex layouts
- Creative interpretation of positioning requests (floating, overlay, background, grid, etc.)
- Context-aware styling that maintains design coherence
- Responsive optimization across all device sizes
- Advanced CSS effects (shadows, transforms, animations, filters)
- Perfect execution of unique creative visions

TECHNICAL EXPERTISE:
- Advanced CSS Grid and Flexbox layouts
- CSS transforms, animations, and transitions
- Media queries for responsive design
- Z-index management and layer composition
- Background positioning and sizing
- Image filters and blend modes
- Video integration and controls
- SVG manipulation and styling

RESPONSE FORMAT:
You must respond with a JSON object containing:
{
  \"html\": \"Complete HTML structure with integrated media\",
  \"css\": \"Complete CSS styles for the integration\",
  \"description\": \"Brief explanation of the implementation\",
  \"responsive_notes\": \"Mobile/tablet considerations\",
  \"creative_elements\": [\"list of creative techniques used\"]
}

INTEGRATION PRINCIPLES:
1. Maintain existing layout structure unless explicitly requested to modify
2. Ensure perfect responsive behavior across all screen sizes
3. Use semantic HTML and clean, efficient CSS
4. Implement creative effects that enhance, not distract
5. Consider accessibility and performance implications
6. Preserve design consistency with existing elements

Always create production-ready code that implements the user's vision perfectly while maintaining professional web standards.";
    }
    
    /**
     * Handle media integration AJAX request
     */
    public function handle_media_integration() {
        // Security check
        if (!check_ajax_referer('vmo_builder_nonce', 'security', false)) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        $this->prepare_long_running_runtime();
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        $user_id = get_current_user_id();
        
        // Validate required parameters
        $media_url = sanitize_url($_POST['media_url'] ?? '');
        $media_type = sanitize_text_field($_POST['media_type'] ?? '');
        $integration_prompt = sanitize_textarea_field($_POST['integration_prompt'] ?? '');
        $current_html = wp_unslash($_POST['current_html'] ?? '');
        $project_context = sanitize_textarea_field($_POST['project_context'] ?? '');
        
        if (empty($media_url) || empty($integration_prompt)) {
            wp_send_json_error(array('message' => 'Missing required parameters'));
            return;
        }
        
        try {
            // ── Idempotency: prevent duplicate charges on retries ──
            $idempotency_key = 'vmo_media_' . md5($user_id . '|' . $media_url . '|' . $integration_prompt);
            $recent = get_transient($idempotency_key);
            if ($recent) {
                // Same exact request within 60s — return cached result, no charge
                wp_send_json_success(json_decode($recent, true));
                return;
            }

            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('media_integration') : 900;
            $description = 'Context-Aware Media Integration: ' . substr($integration_prompt, 0, 100) . '...';

            if (!function_exists('vmo_deduct_tokens') || !vmo_deduct_tokens($user_id, $token_cost, 'media_integration', $description)) {
                $user_balance = (int) get_user_meta($user_id, 'vmo_token_balance', true);
                wp_send_json_error(array(
                    'message' => 'Insufficient token balance. Media integration requires ' . number_format($token_cost) . ' tokens.',
                    'required_tokens' => $token_cost,
                    'current_balance' => $user_balance
                ));
                return;
            }
            
            // Get full project context for AI awareness
            $project_context = $this->get_current_project_context($user_id);
            
            // Prepare media integration data
            $media_data = array(
                'media_url' => $media_url,
                'media_type' => $media_type,
                'integration_prompt' => $integration_prompt
            );
            
            // Generate media integration with full project awareness
            $integration_result = $this->generate_context_aware_integration(
                $media_data,
                $project_context
            );
            
            if (is_wp_error($integration_result)) {
                if (function_exists('vmo_add_tokens')) {
                    vmo_add_tokens($user_id, $token_cost, 'topup', 'Media integration failed - refund');
                }
                wp_send_json_error(array('message' => $integration_result->get_error_message()));
                return;
            }

            $remaining_balance = function_exists('vmo_get_token_balance') ? vmo_get_token_balance($user_id) : max(0, ((int) get_user_meta($user_id, 'vmo_token_balance', true)) - $token_cost);
            
            wp_send_json_success(array(
                'integration' => $integration_result,
                'tokens_used' => $token_cost,
                'remaining_balance' => $remaining_balance
            ));

            // Cache result for idempotency (60 second window)
            set_transient($idempotency_key, json_encode(array(
                'integration' => $integration_result,
                'tokens_used' => $token_cost,
                'remaining_balance' => $remaining_balance,
                'cached' => true,
            )), 60);
            
        } catch (Exception $e) {
            error_log('VMO Media Integration Error: ' . $e->getMessage());
            wp_send_json_error(array('message' => 'Failed to process media integration request'));
        }
    }
    
    /**
     * Generate media integration using OpenAI API
     */
    private function generate_media_integration($media_url, $media_type, $prompt, $current_html, $context) {
        if (!$this->api_key) {
            return new WP_Error('no_api_key', 'AI API key not configured');
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for media integration AI call
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('media_integration') : 900;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'media_integration', 'Media integration AI generation')) {
                return new WP_Error('insufficient_tokens', 'Insufficient tokens. Please top up your balance.');
            }
        }
        
        // Prepare the user prompt
        $user_prompt = $this->build_integration_prompt($media_url, $media_type, $prompt, $current_html, $context);
        
        // ✅ FIX: Use centralized model registry
        $_mi_model = function_exists('vmo_get_model') ? vmo_get_model('mini') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5-mini');
        $request_body = array_merge(array(
            'model' => $_mi_model,
            'messages' => array(
                array(
                    'role' => 'system',
                    'content' => $this->agent_system_prompt
                ),
                array(
                    'role' => 'user',
                    'content' => $user_prompt
                )
            ),
            'temperature' => 0.7,
        ), function_exists('vmo_get_token_param') ? vmo_get_token_param($_mi_model, 3000) : array('max_tokens' => 3000));
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode($request_body),
            'timeout' => 120
        ));
        
        if (is_wp_error($response)) {
            return new WP_Error('api_error', 'AI API request failed: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return new WP_Error('api_error', 'AI API error: ' . $response_code);
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!isset($data['choices'][0]['message']['content'])) {
            return new WP_Error('invalid_response', 'Invalid AI API response');
        }
        
        $ai_response = $data['choices'][0]['message']['content'];
        
        // Parse the JSON response
        $integration_data = json_decode($ai_response, true);
        if (!$integration_data) {
            return new WP_Error('invalid_json', 'Failed to parse AI response as JSON');
        }
        
        // Validate required fields
        $required_fields = array('html', 'css', 'description');
        foreach ($required_fields as $field) {
            if (!isset($integration_data[$field])) {
                return new WP_Error('incomplete_response', "Missing required field: {$field}");
            }
        }
        
        // Sanitize the response
        $integration_data['html'] = wp_kses_post($integration_data['html']);
        $integration_data['css'] = wp_strip_all_tags($integration_data['css']);
        $integration_data['description'] = sanitize_textarea_field($integration_data['description']);
        
        return $integration_data;
    }
    
    /**
     * Build the integration prompt for the AI agent
     */
    private function build_integration_prompt($media_url, $media_type, $prompt, $current_html, $context) {
        $prompt_parts = array();
        
        $prompt_parts[] = "MEDIA INTEGRATION REQUEST:";
        $prompt_parts[] = "Media URL: {$media_url}";
        $prompt_parts[] = "Media Type: {$media_type}";
        $prompt_parts[] = "Integration Request: {$prompt}";
        
        if (!empty($context)) {
            $prompt_parts[] = "\nPROJECT CONTEXT:";
            $prompt_parts[] = $context;
        }
        
        if (!empty($current_html)) {
            $prompt_parts[] = "\nCURRENT HTML STRUCTURE:";
            $prompt_parts[] = substr($current_html, 0, 5000); // Limit size
        }
        
        $prompt_parts[] = "\nPLEASE:";
        $prompt_parts[] = "1. Analyze the integration request and current structure";
        $prompt_parts[] = "2. Create innovative and creative media integration";
        $prompt_parts[] = "3. Ensure responsive design across all devices";
        $prompt_parts[] = "4. Maintain design consistency and professional appearance";
        $prompt_parts[] = "5. Implement the exact creative vision described in the request";
        $prompt_parts[] = "6. Return complete, production-ready HTML and CSS code";
        
        return implode("\n", $prompt_parts);
    }
    
    /**
     * Get integration suggestions based on media type
     */
    public function get_integration_suggestions($media_type) {
        $suggestions = array(
            'image' => array(
                'Place as a floating element with subtle shadow over the hero section',
                'Create a circular mask and position in the top-right corner',
                'Use as a background image with overlay text',
                'Integrate into a CSS Grid layout with hover effects',
                'Create a polaroid-style frame effect positioned diagonally'
            ),
            'video' => array(
                'Embed as a background video with muted autoplay',
                'Create a video modal that opens on button click',
                'Position as a floating video player in corner',
                'Integrate with custom controls and branding',
                'Create a video hero section with overlay content'
            ),
            'svg' => array(
                'Animate SVG elements on scroll',
                'Use as decorative background pattern',
                'Create interactive SVG with hover states',
                'Integrate as logo with smooth animations',
                'Position as floating accent elements'
            )
        );
        
        return $suggestions[$media_type] ?? array();
    }
    
    /**
     * Get current project context for AI awareness
     */
    private function get_current_project_context($user_id) {
        global $wpdb;
        
        $context_data = array();
        
        // Get user's current active project
        $table_name = defined('VMO_PROJECTS_TABLE') ? VMO_PROJECTS_TABLE : $wpdb->prefix . 'vmo_projects';
        
        $current_project = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table_name} WHERE user_id = %d ORDER BY updated_at DESC LIMIT 1",
            $user_id
        ));
        
        if ($current_project) {
            $project_data = json_decode($current_project->project_data, true);
            
            $context_data = array(
                'project_id' => $current_project->id,
                'project_name' => $current_project->project_name,
                'business_type' => $project_data['business_type'] ?? '',
                'current_html' => $project_data['html_content'] ?? '',
                'current_css' => $project_data['css_content'] ?? '',
                'template_name' => $project_data['template'] ?? '',
                'color_scheme' => $project_data['colors'] ?? array(),
                'existing_elements' => $this->extract_existing_elements($project_data['html_content'] ?? ''),
                'layout_structure' => $this->analyze_layout_structure($project_data['html_content'] ?? ''),
                'responsive_breakpoints' => $project_data['responsive_settings'] ?? array()
            );
        }
        
        // Get user's business profile for additional context
        if (function_exists('vmo_get_consultation_profile')) {
            $business_profile = vmo_get_consultation_profile($user_id);
            if (!empty($business_profile)) {
                $context_data['business_profile'] = $business_profile;
            }
        }
        
        return $context_data;
    }
    
    /**
     * Extract existing elements from HTML for context awareness
     */
    private function extract_existing_elements($html) {
        if (empty($html)) return array();
        
        $elements = array();
        
        // Extract common elements
        if (preg_match_all('/<(h[1-6])[^>]*>(.*?)<\/\1>/i', $html, $matches)) {
            $elements['headings'] = array_map('strip_tags', $matches[2]);
        }
        
        if (preg_match_all('/<img[^>]+>/i', $html, $matches)) {
            $elements['existing_images'] = count($matches[0]);
        }
        
        if (preg_match_all('/<video[^>]+>/i', $html, $matches)) {
            $elements['existing_videos'] = count($matches[0]);
        }
        
        if (preg_match_all('/class=["\']([^"\']+)["\']/i', $html, $matches)) {
            $elements['css_classes'] = array_unique($matches[1]);
        }
        
        return $elements;
    }
    
    /**
     * Analyze layout structure for better integration placement
     */
    private function analyze_layout_structure($html) {
        if (empty($html)) return array();
        
        $structure = array(
            'has_header' => stripos($html, '<header') !== false || stripos($html, 'class="header') !== false,
            'has_nav' => stripos($html, '<nav') !== false || stripos($html, 'navigation') !== false,
            'has_hero' => stripos($html, 'hero') !== false,
            'has_sidebar' => stripos($html, 'sidebar') !== false,
            'has_footer' => stripos($html, '<footer') !== false || stripos($html, 'class="footer') !== false,
            'grid_layout' => stripos($html, 'display: grid') !== false || stripos($html, 'grid-') !== false,
            'flex_layout' => stripos($html, 'display: flex') !== false || stripos($html, 'flex-') !== false,
            'container_classes' => $this->extract_container_classes($html)
        );
        
        return $structure;
    }
    
    /**
     * Extract container classes for layout awareness
     */
    private function extract_container_classes($html) {
        $containers = array();
        
        if (preg_match_all('/class=["\']([^"\']*(?:container|wrapper|content|main)[^"\']*)["\']/', $html, $matches)) {
            $containers = array_unique($matches[1]);
        }
        
        return $containers;
    }
    
    /**
     * Build enhanced integration prompt with full project context
     */
    private function build_integration_prompt_with_context($media_data, $project_context) {
        $prompt_parts = array();
        
        $prompt_parts[] = "MEDIA INTEGRATION REQUEST:";
        $prompt_parts[] = "Media URL: " . $media_data['media_url'];
        $prompt_parts[] = "Media Type: " . $media_data['media_type'];
        $prompt_parts[] = "Integration Request: " . $media_data['integration_prompt'];
        
        // Add comprehensive project context
        if (!empty($project_context)) {
            $prompt_parts[] = "\nCURRENT PROJECT CONTEXT:";
            
            if (!empty($project_context['business_type'])) {
                $prompt_parts[] = "Business Type: " . $project_context['business_type'];
            }
            
            if (!empty($project_context['template_name'])) {
                $prompt_parts[] = "Template: " . $project_context['template_name'];
            }
            
            if (!empty($project_context['color_scheme'])) {
                $prompt_parts[] = "Color Scheme: " . json_encode($project_context['color_scheme']);
            }
            
            if (!empty($project_context['layout_structure'])) {
                $prompt_parts[] = "Layout Structure: " . json_encode($project_context['layout_structure']);
            }
            
            if (!empty($project_context['existing_elements'])) {
                $prompt_parts[] = "Existing Elements: " . json_encode($project_context['existing_elements']);
            }
            
            if (!empty($project_context['current_html'])) {
                $prompt_parts[] = "\nCURRENT HTML STRUCTURE:";
                $prompt_parts[] = substr($project_context['current_html'], 0, 4000); // Limit for API
            }
            
            if (!empty($project_context['current_css'])) {
                $prompt_parts[] = "\nCURRENT CSS STYLES:";
                $prompt_parts[] = substr($project_context['current_css'], 0, 2000); // Limit for API
            }
        }
        
        $prompt_parts[] = "\nINTEGRATION REQUIREMENTS:";
        $prompt_parts[] = "1. Analyze the existing project structure and design";
        $prompt_parts[] = "2. Integrate the media in a way that enhances the current design";
        $prompt_parts[] = "3. Ensure the integration doesn't conflict with existing elements";
        $prompt_parts[] = "4. Maintain responsive behavior across all devices";
        $prompt_parts[] = "5. Use creative and professional placement techniques";
        $prompt_parts[] = "6. Return production-ready HTML and CSS code";
        
        return implode("\n", $prompt_parts);
    }
    
    /**
     * Generate context-aware media integration using OpenAI API
     */
    private function generate_context_aware_integration($media_data, $project_context) {
        if (empty($this->api_key)) {
            return new WP_Error('no_api_key', 'AI API key not configured.');
        }
        
        // Token deduction handled by caller (handle_media_integration) — do not double-deduct here
        
        // Build comprehensive prompt with full project context
        $user_prompt = $this->build_integration_prompt_with_context($media_data, $project_context);
        
        // ✅ FIX: Use centralized model registry
        $_mi_model2 = function_exists('vmo_get_model') ? vmo_get_model('mini') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5-mini');
        $request_body = array_merge(array(
            'model' => $_mi_model2,
            'messages' => array(
                array(
                    'role' => 'system',
                    'content' => $this->agent_system_prompt
                ),
                array(
                    'role' => 'user',
                    'content' => $user_prompt
                )
            ),
            'temperature' => 0.7,
            'top_p' => 0.9
        ), function_exists('vmo_get_token_param') ? vmo_get_token_param($_mi_model2, 2500) : array('max_tokens' => 2500));
        
        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($request_body),
            'timeout' => 60,
        );
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);

        // Fallback Logic
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) >= 400) {
            $request_body['model'] = function_exists('vmo_get_model') ? vmo_get_model('fallback') : 'gpt-5.5-nano';
            $args['body'] = json_encode($request_body);
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        }
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return new WP_Error('api_error', 'AI API request failed with code: ' . $response_code);
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!isset($data['choices'][0]['message']['content'])) {
            return new WP_Error('invalid_response', 'Invalid response from AI API');
        }
        
        $ai_response = $data['choices'][0]['message']['content'];
        
        // Parse the JSON response from AI
        $integration_data = json_decode($ai_response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            // If not valid JSON, treat as plain text response
            $integration_data = array(
                'html' => '',
                'css' => '',
                'description' => $ai_response,
                'responsive_notes' => 'Please review the integration for responsive behavior',
                'creative_elements' => array('Custom AI-generated integration')
            );
        }
        
        // Enhance integration data with project context information
        $integration_data['project_context_used'] = !empty($project_context);
        $integration_data['integration_timestamp'] = current_time('mysql');
        
        return $integration_data;
    }
}

// Initialize the Media Integration Agent
new VMO_Media_Integration_Agent();
