<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * AI页面构建器主类 - 重构为前后端分离架构
 */

class PufferGo_AI_Page_Builder {
    
    public function __construct() {
        // REST API路由需要随时可用（前后端都需要）
        add_action('rest_api_init', array($this, 'register_api'));

        // 后台脚本只在后台加载（性能优化）
        if (is_admin()) {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        }
    }
    
    /**
     * 注册REST API
     */
    public function register_api() {
        // 第二阶段：匹配 Patterns
        register_rest_route('puffergo/v1', '/match-patterns', array(
            'methods' => 'POST',
            'callback' => array($this, 'match_patterns'),
            'permission_callback' => array($this, 'check_permission'),
        ));
    }
    
    /**
     * 检查权限
     */
    public function check_permission() {
        return current_user_can('edit_posts');
    }
    
    /**
     * 只在编辑页面加载脚本和资源
     */
    public function enqueue_scripts($hook) {
        // AI Page Builder sidebar removed from edit page UI (option no longer shown).
        return;

        // 只在文章/页面编辑页面加载
        $screen = get_current_screen();
        if ( ! $screen || ! in_array( $screen->base, array( 'post', 'post-new' ), true ) ) {
            return;
        }
        
        // 加载React应用的编译产物（通过特殊区块）
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        $asset_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-admin-app/index.asset.php';
        
        // 如果asset文件存在，使用其中的依赖和版本信息
        if (file_exists($asset_file)) {
            $asset = include $asset_file;
            $dependencies = $asset['dependencies'];
            $version = $asset['version'];
        } else {
            // 回退方案：手动指定依赖
            $dependencies = array(
                'wp-element',
                'wp-components',
                'wp-api-fetch',
                'wp-data',
                'wp-hooks'
            );
            $version = filemtime(plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-admin-app/index.js');
        }
        
        // 加载JavaScript（AI应用编译产物）
        wp_enqueue_script(
            'puffergo-ai-page-builder',
            $plugin_url . 'build/blocks/ai-admin-app/index.js',
            $dependencies,
            $version,
            true
        );
        
        // 加载 CSS - 组件样式（Tailwind 已在全局统一加载）
        $style_css_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-admin-app/style-index.css';
        if (file_exists($style_css_file)) {
            wp_enqueue_style(
                'puffergo-ai-page-builder',
                $plugin_url . 'build/blocks/ai-admin-app/style-index.css',
                array('puffergo-admin-tailwind'), // 依赖全局 Tailwind
                $version
            );
        }
        
        // 通过wp_localize_script安全地传递数据给前端（两阶段版本）
        $theme_bridge = new PufferGo_Theme_Bridge();
        wp_localize_script('puffergo-ai-page-builder', 'puffergoAiPageBuilder', array(
            'restUrl' => rest_url('puffergo/v1/'),
            'nonce' => wp_create_nonce('wp_rest'),
            'currentUserId' => get_current_user_id(),
            'currentPostId' => get_the_ID(),
            'themeCssVars' => $theme_bridge->get_css_variables(),
            'strings' => array(
                // 通用
                'close' => __('关闭', 'puffergo'),
                'inputRequired' => __('请输入页面需求描述', 'puffergo'),
                
                // 第一阶段
                'phase1Title' => __('规划页面结构', 'puffergo'),
                'phase1Button' => __('开始规划页面', 'puffergo'),
                'phase1Loading' => __('AI 正在规划页面结构...', 'puffergo'),
                'phase1Success' => __('页面结构规划完成！请确认后继续', 'puffergo'),
                'phase1Error' => __('页面规划失败', 'puffergo'),
                
                // 第二阶段
                'phase2Title' => __('生成 HTML/CSS', 'puffergo'),
                'phase2Button' => __('确认并生成页面', 'puffergo'),
                'phase2Loading' => __('AI 正在生成 HTML/CSS...', 'puffergo'),
                'phase2Success' => __('HTML/CSS 生成完成！', 'puffergo'),
                'phase2Error' => __('HTML/CSS 生成失败', 'puffergo'),
                
                // 插入
                'insertButton' => __('插入到编辑器', 'puffergo'),
                'insertingBlocks' => __('正在插入区块...', 'puffergo'),
                /* translators: %d is the number of blocks inserted */
                'insertSuccess' => __('已成功插入 %d 个区块', 'puffergo'),
                'insertError' => __('插入区块失败', 'puffergo'),
                
                // 其他
                'copySuccess' => __('内容已复制到剪贴板！', 'puffergo'),
                'reset' => __('重新开始', 'puffergo'),
                'back' => __('返回', 'puffergo'),
            )
        ));
        
        // Pattern生成器的配置数据
        wp_localize_script('puffergo-ai-page-builder', 'puffergoPatternGenerator', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('puffergo_pattern_generator'),
            'strings' => array(
                'success' => __('Pattern创建成功！', 'puffergo'),
                'error' => __('创建失败，请重试', 'puffergo'),
                'processing' => __('正在处理...', 'puffergo')
            )
        ));
        
        // 添加React应用的挂载点
        add_action('admin_footer', array($this, 'render_ai_root_element'));
    }
    
    /**
     * 渲染React应用的挂载点
     */
    public function render_ai_root_element() {
        echo '<div id="puffergo-ai-page-builder-root"></div>';
    }
    
    /**
     * 【第二阶段】匹配 Patterns
     * 接收页面结构和 patterns，调用 AI 进行匹配
     */
    public function match_patterns($request) {
        puffergo_log('=== AI Page Builder: 第二阶段 - 开始匹配 Patterns ===');
        $start_time = microtime(true);
        
        $params = $request->get_json_params();
        $pages = $params['pages'] ?? array();
        
        // 验证输入
        if (empty($pages) || !is_array($pages)) {
            puffergo_log('AI Page Builder 错误: pages 参数无效');
            return new WP_REST_Response([
                'success' => false,
                'message' => '请提供有效的页面信息'
            ], 400);
        }
        
        puffergo_log('AI Page Builder: 准备为 ' . count($pages) . ' 个页面匹配 patterns');
        
        try {
            // 获取可用的 patterns
            // $patterns_start_time = microtime(true);
            // $patterns = $this->get_available_blocks();
            // $patterns_duration = microtime(true) - $patterns_start_time;
            
            // puffergo_log('AI Page Builder: 获取到 ' . count($patterns) . ' 个可用 patterns，耗时: ' . round($patterns_duration, 4) . ' 秒');
            // puffergo_log('AI Page Builder:$patterns====>: ' . json_encode($patterns, JSON_UNESCAPED_UNICODE));
            // 调用 AI 服务进行匹配
            $ai_start_time = microtime(true);
            $result = $this->call_ai_match_patterns([], $pages);
            $ai_duration = microtime(true) - $ai_start_time;
            
            $total_duration = microtime(true) - $start_time;
            
            puffergo_log('AI Page Builder: Pattern 匹配完成');
            puffergo_log('AI Page Builder: AI 推荐了 ' . (isset($result['patterns']) ? count($result['patterns']) : 0) . ' 个 patterns');
            puffergo_log('=== AI Page Builder: 第二阶段结束（成功）===');

 
            // puffergo_log('AI Page Builder:$result_patterns====>: ' . json_encode($result_patterns, JSON_UNESCAPED_UNICODE));

            
            return new WP_REST_Response([
                'success' => true,
                'data' => array(
                    'patterns' => $result['patterns'] ?? array(),
                    'reasoning' => $result['reasoning'] ?? '',
                    'timing' => array(
                        'ai_matching' => round($ai_duration, 4),
                        'total' => round($total_duration, 4)
                    )
                )
            ], 200);
            
        } catch (PufferGo_API_Exception $e) {
            // 认证/计费相关错误 - 透传状态码和操作 URL
            $duration = microtime(true) - $start_time;
            puffergo_log('AI Page Builder 错误 (API): ' . $e->getMessage() . ' (Code: ' . $e->getCode() . ')');
            puffergo_log('=== AI Page Builder: 第二阶段结束（失败）===');
            
            $response_data = $e->toArray();
            $response_data['timing'] = array('total' => round($duration, 4));
            return new WP_REST_Response($response_data, $e->getCode());
        } catch (Exception $e) {
            $duration = microtime(true) - $start_time;
            puffergo_log('AI Page Builder 错误: ' . $e->getMessage());
            puffergo_log('=== AI Page Builder: 第二阶段结束（失败）===');
            
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Pattern 匹配失败：' . $e->getMessage(),
                'timing' => array(
                    'total' => round($duration, 4)
                )
            ], 500);
        }
    }
    
    /**
     * 获取可用 Patterns - 从 Design Library 获取
     */
    private function get_available_blocks() {
        puffergo_log('=== AI Page Builder: 开始获取可用 Patterns ===');
        $start_time = microtime(true);
        
        $patterns = array();
        
        // 通过内部 API 调用获取 patterns（避免重复实例化 Design Library）
        try {
            $patterns_response = $this->call_ai_service_get_patterns(array(), array(
                'status' => 'publish',
                'per_page' => -1
            ));

            if (isset($patterns_response['patterns'])) {
                $raw_patterns = $patterns_response['patterns'];
                puffergo_log('AI Page Builder: 成功获取 ' . count($raw_patterns) . ' 个 patterns');
                
                // 处理每个 pattern，只保留需要的字段
                foreach ($raw_patterns as $pattern) {
                    // 解析 classification JSON
                    // 这里已经是JSON了，没必要再解码
                    $classification = null;
                    if (!empty($pattern['classification'])) {
                        $classification = $pattern['classification'];
                    }
                    
                    // 解析 schema JSON
                    // 这里已经是JSON了，没必要再解码
                    $schema = null;
                    if (!empty($pattern['schema'])) {
                        $schema = $pattern['schema'];
                    }
                    
                    // 获取 HTML 模板
                    $html_template = $pattern['html_template'] ?? '';
                    
                    // 提取需要的字段
                    $processed_pattern = array(
                        'id' => $pattern['id'],
                        'title' => $pattern['title'],
                        // 从 classification 中提取字段
                        'summary' => '',
                        'details' => '',
                        'html_template' => $html_template, // 使用 HTML 模板替代 content
                        'content' => $pattern['content'] ?? '', // 保留用于兼容
                        'thumbnail_url' => $pattern['thumbnail_url'] ?? '',
                        'schema' => $schema ?? array('fields' => array()), // schema 数据
                        'pattern_category' => '',
                        'applicable_page_types' => array(),
                        'industry' => array(),
                        'style' => array(),
                        'layout_structure' => '',
                        'item_capacity' => ''
                    );
                    
                    if ($classification) {
                        // 从 narrative 中提取 summary 和 details
                        if (isset($classification['narrative'])) {
                            $processed_pattern['summary'] = $classification['narrative']['summary'] ?? '';
                            $processed_pattern['details'] = $classification['narrative']['details'] ?? '';
                        }
                        
                        // 从 classification 中提取其他字段
                        if (isset($classification['classification'])) {
                            $class_data = $classification['classification'];
                            $processed_pattern['pattern_category'] = $class_data['pattern_category'] ?? '';
                            $processed_pattern['applicable_page_types'] = $class_data['applicable_page_types'] ?? array();
                            $processed_pattern['industry'] = $class_data['industry'] ?? array();
                            $processed_pattern['style'] = $class_data['style'] ?? array();
                            $processed_pattern['layout_structure'] = $class_data['layout_structure'] ?? '';
                            $processed_pattern['item_capacity'] = $class_data['item_capacity'] ?? '';
                        }
                    }
                    
                    $patterns[] = $processed_pattern;
                    
                    puffergo_log('AI Page Builder: 处理 pattern - ID: ' . $pattern['id'] . ', 标题: ' . $pattern['title'] . ', 分类: ' . $processed_pattern['pattern_category']);
                }
            } else {
                puffergo_log('AI Page Builder 错误: API 返回数据格式不正确');
            }
        } catch (Exception $e) {
            puffergo_log('AI Page Builder 错误: 获取 patterns 失败 - ' . $e->getMessage());
        }
        
        $duration = microtime(true) - $start_time;
        puffergo_log('AI Page Builder: 获取 patterns 完成，耗时: ' . round($duration, 4) . ' 秒，共 ' . count($patterns) . ' 个');
        puffergo_log('=== AI Page Builder: 结束获取可用 Patterns ===');
        
        return $patterns;
    }
    
    /**
     * 调用 AI 服务匹配 Patterns（第二阶段）
     * @param array $patterns 这里的content是没有的
     * @param array $pages
     * @return array
     */
    private function call_ai_match_patterns($patterns, $pages) {
        $api_client = PufferGo_API_Client::get_instance();
        
        puffergo_log('AI Page Builder: 发送 ' . count($patterns) . ' 个 patterns 和 ' . count($pages) . ' 个页面');
        
        try {
            $result = $api_client->post(
                '/api/site-builder/pattern-selector',
                array(
                    'patterns' => $patterns,
                    'pages' => $pages
                ),
                array(
                    'timeout' => 205,
                    'log_prefix' => 'AI Page Builder'
                )
            );
            
            $patterns_count = isset($result['patterns']) ? count($result['patterns']) : 0;
            puffergo_log('AI Page Builder: Pattern 匹配成功，返回 ' . $patterns_count . ' 个推荐');
            if (!empty($result['reasoning'])) {
                puffergo_log('AI Page Builder: 推理过程: ' . $result['reasoning']);
            }
            
            return array(
                'patterns' => $result['patterns'] ?? array(),
                'reasoning' => $result['reasoning'] ?? ''
            );
        } catch (Exception $e) {
            puffergo_log('AI Page Builder 错误: ' . $e->getMessage());
            throw $e;
        }
    }
}
