<?php
namespace IntentDeep\VirtualFiles\Controllers;

use IntentDeep\VirtualFiles\Core\Option;

class AiController {
    /**
     * Handle AI content generation request
     */
    public function generate_content() {
        // Verify nonce
        if (!check_ajax_referer('intentdeep_vf_ai_generation', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', 'intentdeep-virtual-files')]);
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => __('You do not have permission to perform this action.', 'intentdeep-virtual-files')]);
        }

        // Get AI Settings
        $options = Option::all();
        $provider = isset($options['ai_provider']) ? $options['ai_provider'] : 'openrouter';
        $model = isset($options['ai_model']) ? $options['ai_model'] : 'google/gemini-2.5-flash-lite';

        // Get Provider-Specific Key
        // For OpenRouter, we check the specific key first, then fallback to the generic key for backward compatibility
        if ($provider === 'openrouter') {
            $api_key = isset($options['ai_api_key_openrouter']) && !empty($options['ai_api_key_openrouter'])
                ? $options['ai_api_key_openrouter']
                : (isset($options['ai_api_key']) ? $options['ai_api_key'] : '');
        } else {
            $key_name = 'ai_api_key_' . $provider;
            $api_key = isset($options[$key_name]) ? trim($options[$key_name]) : '';
        }

        if (empty($api_key)) {
            wp_send_json_error(['message' => sprintf(__('API Key for %s is missing. Please add it in Settings.', 'intentdeep-virtual-files'), ucfirst($provider))]);
        }

        // Get request data
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        $file_type = isset($_POST['extension']) ? sanitize_text_field($_POST['extension']) : 'txt';
        $action_type = isset($_POST['action_type']) ? sanitize_text_field($_POST['action_type']) : 'generate';
        $current_content = isset($_POST['current_content']) ? stripslashes($_POST['current_content']) : ''; // Preserve code formatting
        $stream = isset($_POST['stream']) && $_POST['stream'] === 'true';

        if (empty($prompt)) {
            wp_send_json_error(['message' => __('Prompt cannot be empty.', 'intentdeep-virtual-files')]);
        }

        // Construct system message
        if ($action_type === 'improve') {
            $system_message = "You are an expert developer assistant. Your task is to IMPROVE or FIX the provided content for a virtual file with extension '.{$file_type}' based on the user's instructions. ";
            $system_message .= "Maintain the existing structure unless asked to change it. ";
        } elseif ($action_type === 'analyze') {
            $system_message = "You are an expert developer assistant. Your task is to ANALYZE the provided content for a virtual file with extension '.{$file_type}'. ";
            $system_message .= "Explain what the code does, identify any potential errors, security risks, or improvements. Keep the explanation concise and helpful. Use Markdown for formatting.";
        } else {
            $system_message = "You are an expert developer assistant. Your task is to generate content for a virtual file with extension '.{$file_type}'. ";
        }

        if ($action_type !== 'analyze') {
            $system_message .= "Provide ONLY the raw file content. Do not include markdown code blocks (like ```json ... ```), explanations, or any other text. ";

            if ($file_type === 'json') {
                $system_message .= "Ensure the output is valid JSON.";
            } elseif ($file_type === 'xml' || $file_type === 'rss') {
                $system_message .= "Ensure the output is valid XML.";
            } elseif ($file_type === 'robots.txt' || $file_type === 'txt') {
                $system_message .= "Ensure the output follows standard format for this file type.";
            }
        }

        // Gather and Attach Context
        $site_context = $this->get_site_context();
        $system_message .= "\n\nSite Context: " . json_encode($site_context);

        // Handle Attached Posts
        $attached_content = '';
        if (isset($_POST['attached_posts']) && is_array($_POST['attached_posts'])) {
            $attached_ids = array_map('intval', $_POST['attached_posts']);
            $attached_ids = array_slice($attached_ids, 0, 3); // Max 3 limit logic

            if (!empty($attached_ids)) {
                $attached_content = $this->get_post_content($attached_ids);
            }
        }

        // Build User Message
        $user_message = $prompt;

        if (!empty($attached_content)) {
            $user_message .= "\n\n--- ATTACHED WEBSITE DATA ---\n" . $attached_content;
        }

        if (($action_type === 'improve' || $action_type === 'analyze') && !empty($current_content)) {
            $prefix = ($action_type === 'analyze') ? "Content to Analyze:\n\n" : "Original Content:\n\n";
            $suffix = ($action_type === 'analyze') ? "\n\nSpecific Analysis Request:\n" : "\n\nInstructions to Improve/Fix:\n";

            $user_message = $prefix . $current_content . $suffix . $user_message;
        }

        // Configure Request based on Provider
        $apiUrl = '';
        $headers = [];
        $body = [];

        if ($provider === 'anthropic') {
            // Anthropic Native API Format
            $apiUrl = 'https://api.anthropic.com/v1/messages';

            $headers = [
                'x-api-key' => $api_key,
                'anthropic-version' => '2023-06-01',
                'content-type' => 'application/json'
            ];

            $body = [
                'model' => $model,
                'max_tokens' => 4096,
                'system' => $system_message,
                'messages' => [
                    ['role' => 'user', 'content' => $user_message]
                ],
                'stream' => $stream
            ];
        } else {
            // OpenAI Compatible Providers (OpenRouter, OpenAI, Google)
            if ($provider === 'openai') {
                $apiUrl = 'https://api.openai.com/v1/chat/completions';
            } elseif ($provider === 'google') {
                $apiUrl = 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions';
            } else {
                // Default to OpenRouter
                $apiUrl = 'https://openrouter.ai/api/v1/chat/completions';
            }

            $headers = [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ];

            $body = [
                'model' => $model,
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => $system_message
                    ],
                    [
                        'role' => 'user',
                        'content' => $user_message
                    ]
                ],
                'temperature' => 0.7,
                'max_tokens' => 4096,
                'stream' => $stream
            ];
        }

        // Handle Streaming
        if ($stream) {
            // Disable timeouts and buffering
            if (function_exists('set_time_limit')) set_time_limit(0);
            if (ob_get_level()) ob_end_clean();

            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('X-Accel-Buffering: no'); // Nginx

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

            // Format headers for cURL
            $curl_headers = [];
            foreach ($headers as $k => $v) {
                $curl_headers[] = "$k: $v";
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);

            // Initialize buffer for incomplete lines
            $buffer = '';

            // Callback for streaming
            curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$buffer, $provider) {
                $buffer .= $data;
                $lines = explode("\n", $buffer);
                $buffer = array_pop($lines); // Keep last part

                foreach ($lines as $line) {
                    $line = trim($line);
                    if (empty($line)) continue;

                    if ($provider === 'anthropic') {
                        // Handle Anthropic SSE format (event: ..., data: ...)
                        if (strpos($line, 'data: ') === 0) {
                            $json = substr($line, 6);
                            $chunk = json_decode($json, true);

                            if (isset($chunk['type']) && $chunk['type'] === 'content_block_delta') {
                                if (isset($chunk['delta']['text'])) {
                                    echo "data: " . json_encode(['content' => $chunk['delta']['text']]) . "\n\n";
                                    flush();
                                }
                            }
                        }
                    } else {
                        // Handle OpenAI/OpenRouter SSE format
                        if ($line === 'data: [DONE]') continue;

                        if (strpos($line, 'data: ') === 0) {
                            $json = substr($line, 6);
                            $chunk = json_decode($json, true);

                            if (isset($chunk['choices'][0]['delta']['content'])) {
                                echo "data: " . json_encode(['content' => $chunk['choices'][0]['delta']['content']]) . "\n\n";
                                flush();
                            }
                        }
                    }
                }
                return strlen($data);
            });

            curl_exec($ch);
            curl_close($ch);
            exit;
        }

        // Standard Non-Streaming Request (Fallback)
        $response = wp_remote_post($apiUrl, [
            'headers' => $headers,
            'body' => json_encode($body),
            'timeout' => 30
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => 'API Request Failed: ' . $response->get_error_message()]);
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);

        if ($response_code !== 200) {
            $error_msg = isset($data['error']['message']) ? $data['error']['message'] : 'Unknown API error';
            wp_send_json_error(['message' => 'API Error (' . $response_code . '): ' . $error_msg]);
        }

        $content = '';
        if ($provider === 'anthropic' && isset($data['content'][0]['text'])) {
            $content = $data['content'][0]['text'];
        } elseif (isset($data['choices'][0]['message']['content'])) {
            $content = $data['choices'][0]['message']['content'];
        }

        if ($content !== '') {
            // Clean up any potential markdown code blocks if the AI ignored instructions
            if ($action_type !== 'analyze') {
                $content = preg_replace('/^```[a-z]*\s*/i', '', $content);
                $content = preg_replace('/\s*```$/', '', $content);
            }

            wp_send_json_success(['content' => trim($content)]);
        } else {
            wp_send_json_error(['message' => 'Invalid response format from API']);
        }
    }

    /**
     * Gather implicit site context (low token cost)
     */
    private function get_site_context(): array {
        $context = [
            'site_name' => get_bloginfo('name'),
            'site_url' => home_url(),
            'tagline' => get_bloginfo('description'),
            'language' => get_bloginfo('language'),
            'wordpress_version' => get_bloginfo('version'),
            'theme' => wp_get_theme()->get('Name'),
        ];

        // Get active plugins (slugs only) to help AI identify environment (e.g., WooCommerce, Yoast)
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $all_plugins = get_plugins();
        $active_plugins = get_option('active_plugins');
        $plugin_names = [];

        foreach ($active_plugins as $plugin_path) {
            if (isset($all_plugins[$plugin_path])) {
                $plugin_names[] = $all_plugins[$plugin_path]['Name'];
            }
        }

        // Limit to top 20 plugins to save tokens
        $context['active_plugins'] = array_slice($plugin_names, 0, 20);

        // Detect SEO plugin and sitemap URL
        $context['sitemap_url'] = $this->detect_sitemap_url($plugin_names);

        // Detect WooCommerce
        $context['has_woocommerce'] = in_array('WooCommerce', $plugin_names);

        return $context;
    }

    /**
     * Detect the correct sitemap URL based on active SEO plugins
     */
    private function detect_sitemap_url(array $plugin_names): string {
        // Check for Yoast SEO
        if (in_array('Yoast SEO', $plugin_names)) {
            return home_url('/sitemap_index.xml');
        }

        // Check for Rank Math
        foreach ($plugin_names as $plugin) {
            if (stripos($plugin, 'Rank Math') !== false) {
                return home_url('/sitemap_index.xml');
            }
        }

        // Check for All in One SEO
        foreach ($plugin_names as $plugin) {
            if (stripos($plugin, 'All in One SEO') !== false) {
                return home_url('/sitemap.xml');
            }
        }

        // WordPress core sitemap (WP 5.5+)
        global $wp_version;
        if (version_compare($wp_version, '5.5', '>=')) {
            return home_url('/wp-sitemap.xml');
        }

        // Default fallback
        return home_url('/sitemap.xml');
    }

    /**
     * Fetch content for attached posts
     */
    private function get_post_content(array $post_ids): string {
        $output = "";

        $posts = get_posts([
            'include' => $post_ids,
            'post_type' => 'any',
            'post_status' => 'publish',
            'numberposts' => 3
        ]);

        foreach ($posts as $post) {
            $output .= "\n--- Item: " . $post->post_title . " (" . $post->post_type . ") ---\n";
            $output .= "URL: " . get_permalink($post->ID) . "\n";
            $output .= "Content: " . wp_strip_all_tags($post->post_content) . "\n"; // Strip HTML to save tokens
        }

        return $output;
    }

    /**
     * AJAX Handler: Search posts for context attachment
     */
    public function search_posts() {
        // Verify nonce
        if (!check_ajax_referer('intentdeep_vf_ai_generation', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed.', 'intentdeep-virtual-files')]);
        }

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => __('Permission denied.', 'intentdeep-virtual-files')]);
        }

        $search = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';
        if (strlen($search) < 3) {
            wp_send_json_success([]); // Return empty if too short
        }

        $query = new \WP_Query([
            's' => $search,
            'post_type' => 'any',
            'post_status' => 'publish',
            'posts_per_page' => 10,
            'fields' => 'ids' // Fetch only IDs first for performance
        ]);

        $results = [];
        if ($query->have_posts()) {
            foreach ($query->posts as $post_id) {
                $post = get_post($post_id);
                $results[] = [
                    'id' => $post->ID,
                    'title' => $post->post_title,
                    'type' => $post->post_type
                ];
            }
        }

        wp_send_json_success($results);
    }
}
