<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_AI_Page_Builder
{
    public function __construct()
    {
        add_action('rest_api_init', array($this, 'register_api'));

        if (is_admin()) {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        }
    }

    public function register_api()
    {
        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)
    {
        return;
        $screen = get_current_screen();

        if (! $screen || ! in_array($screen->base, array('post', 'post-new'), true)) {
            return;
        } $plugin_url = plugin_dir_url(dirname(__FILE__));
        $asset_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-admin-app/index.asset.php';

        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');
        } wp_enqueue_script('puffergo-ai-page-builder', $plugin_url . 'build/blocks/ai-admin-app/index.js', $dependencies, $version, true);
        $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'), $version);
        } $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(), 'quickStyleCss' => PufferGo_Theme_Bridge::get_quick_style_css(), 'coreCssUrl' => plugins_url('assets/css/puffergo.css', PUFFERGO_PLUGIN_FILE), 'strings' => array('close' => __('Close', 'puffergo'), 'inputRequired' => __('Please enter page requirements', 'puffergo'), 'phase1Title' => __('Plan Page Structure', 'puffergo'), 'phase1Button' => __('Start Planning', 'puffergo'), 'phase1Loading' => __('AI is planning page structure...', 'puffergo'), 'phase1Success' => __('Page structure planning complete! Please confirm to continue', 'puffergo'), 'phase1Error' => __('Page planning failed', 'puffergo'), 'phase2Title' => __('Generate HTML/CSS', 'puffergo'), 'phase2Button' => __('Confirm & Generate Page', 'puffergo'), 'phase2Loading' => __('AI is generating HTML/CSS...', 'puffergo'), 'phase2Success' => __('HTML/CSS generation complete!', 'puffergo'), 'phase2Error' => __('HTML/CSS generation failed', 'puffergo'), 'insertButton' => __('Insert to Editor', 'puffergo'), 'insertingBlocks' => __('Inserting blocks...', 'puffergo'), 'insertSuccess' => __('Successfully inserted %d blocks', 'puffergo'), 'insertError' => __('Failed to insert blocks', 'puffergo'), 'copySuccess' => __('Content copied to clipboard!', 'puffergo'), 'reset' => __('Start Over', 'puffergo'), 'back' => __('Back', 'puffergo'), )));
        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 created successfully!', 'puffergo'), 'error' => __('Creation failed, please try again', 'puffergo'), 'processing' => __('Processing...', 'puffergo'))));
        add_action('admin_footer', array($this, 'render_ai_root_element'));
    }

    public function render_ai_root_element()
    {
        echo '<div id="puffergo-ai-page-builder-root"></div>';
    }

    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' => __('Please provide valid page information.', 'puffergo')], 400);
        } puffergo_log('AI Page Builder: 准备为 ' . count($pages) . ' 个页面匹配 patterns');

        try {
            $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: 第二阶段结束（成功）===');

            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) {
            $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);
        }
    }

    private function get_available_blocks()
    {
        puffergo_log('=== AI Page Builder: 开始获取可用 Patterns ===');
        $start_time = microtime(true);
        $patterns = array();

        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');

                foreach ($raw_patterns as $pattern) {
                    $classification = null;

                    if (!empty($pattern['classification'])) {
                        $classification = $pattern['classification'];
                    } $schema = null;

                    if (!empty($pattern['schema'])) {
                        $schema = $pattern['schema'];
                    } $html_template = $pattern['html_template'] ?? '';
                    $processed_pattern = array('id' => $pattern['id'], 'title' => $pattern['title'], 'summary' => '', 'details' => '', 'html_template' => $html_template, 'content' => $pattern['content'] ?? '', 'thumbnail_url' => $pattern['thumbnail_url'] ?? '', 'schema' => $schema ?? array('fields' => array()), 'pattern_category' => '', 'applicable_page_types' => array(), 'industry' => array(), 'style' => array(), 'layout_structure' => '', 'item_capacity' => '');

                    if ($classification) {
                        if (isset($classification['narrative'])) {
                            $processed_pattern['summary'] = $classification['narrative']['summary'] ?? '';
                            $processed_pattern['details'] = $classification['narrative']['details'] ?? '';
                        }

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;
    }

    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;
        }
    }
}
