<?php
if (! defined('ABSPATH')) {
    exit;
} require_once __DIR__ . '/class-generic-text-replacer.php';
class PufferGo_AI_Site_Builder
{
    public function __construct()
    {
        puffergo_log('🔥 PufferGo_AI_Site_Builder: Constructor called');
        add_action('rest_api_init', array($this, 'register_api'));
        add_action('wp_insert_post', array($this, 'maybe_set_default_template'), 10, 2);
        add_action('wp_enqueue_scripts', array($this, 'enqueue_fullpage_template_styles'), 100);

        if (is_admin()) {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        } add_filter('rank_math/focus_keyword/maxtags', array($this, 'rank_math_focus_keyword_maxtags'));
    }

    public function rank_math_focus_keyword_maxtags()
    {
        return 6;
    }

    public function maybe_set_default_template($post_id, $post)
    {
        static $processed = array();

        if (isset($processed[$post_id])) {
            return;
        } $processed[$post_id] = true;

        if ($post->post_type !== 'page') {
            return;
        } $default_template = get_option('puffergo_default_page_template', '');

        if (empty($default_template) || $default_template === 'default') {
            return;
        } $current = get_post_meta($post_id, '_wp_page_template', true);

        if (empty($current) || $current === 'default') {
            update_post_meta($post_id, '_wp_page_template', $default_template);
        }
    }

    public function enqueue_fullpage_template_styles()
    {
        if (is_admin()) {
            return;
        } $is_fullpage_page = false;
        $is_product = is_singular('puffergo_product');
        $is_product_archive = is_post_type_archive('puffergo_product') || is_tax('puffergo_product_cat');
        $is_blog = is_singular('post') || is_category() || is_post_type_archive('post') || (is_home() && ! is_front_page());
        $cpt_view_post_types = array('puffergo_solution', 'puffergo_case', 'puffergo_testimonial');
        $cpt_view_taxonomies = array('puffergo_solution_cat', 'puffergo_case_cat', 'puffergo_testimonial_industry');
        $is_cpt_view = is_singular($cpt_view_post_types) || is_post_type_archive($cpt_view_post_types) || is_tax($cpt_view_taxonomies);

        if (is_singular('page')) {
            $page_id = get_queried_object_id();

            if ($page_id) {
                $template = get_post_meta($page_id, '_wp_page_template', true);

                if ($template === 'puffergo-fullpage.php') {
                    $is_fullpage_page = true;
                }
            }
        } $is_woo_takeover = false;

        if (class_exists('PufferGo_Business_Mode') && function_exists('is_shop')) {
            if (is_product() && PufferGo_Business_Mode::takeover_single()) {
                $is_woo_takeover = true;
            } elseif ((is_shop() || is_product_category()) && PufferGo_Business_Mode::takeover_archive()) {
                $is_woo_takeover = true;
            }
        }

if (! $is_fullpage_page && ! $is_product && ! $is_product_archive && ! $is_blog && ! $is_cpt_view && ! $is_woo_takeover && ! is_404()) {
            return;
        } $version = defined('PUFFERGO_CORE_VERSION') ? PUFFERGO_CORE_VERSION : '1.0.0';
        $base = plugins_url('assets/css/', PUFFERGO_PLUGIN_FILE);
        wp_enqueue_style('puffergo-tailwind', $base . 'tailwind.css', array('puffergo'), $version);
        wp_enqueue_style('puffergo-token-bridge', $base . 'token-bridge.css', array('puffergo-tailwind'), $version);
        $this->maybe_enqueue_per_template_scaffold_component_styles($version);
        wp_add_inline_style('puffergo', 'body { background-color: #fff !important; }');
    }

    private function maybe_enqueue_per_template_scaffold_component_styles($version)
    {
        if (is_admin() || ! class_exists('PufferGo_Template_Loader')) {
            return;
        } $targets = $this->get_scaffold_style_targets();
        $base = plugins_url('assets/css/', PUFFERGO_PLUGIN_FILE);

        foreach ($targets as $type => $target) {
            if (! is_callable($target['active_callback'])) {
                continue;
            } $active = call_user_func($target['active_callback']);

            if (! is_string($active) || '' === $active) {
                continue;
            } $asset_path = PUFFERGO_PLUGIN_DIR . '/assets/css/' . $target['asset_file'];

            if (! is_readable($asset_path) || 0 === (int) filesize($asset_path)) {
                continue;
            } $asset_ver = (string) filemtime($asset_path);

            if ('' === $asset_ver) {
                $asset_ver = $version;
            } wp_enqueue_style('puffergo-tpl-' . sanitize_key($type) . '-components', esc_url($base . $target['asset_file']), array('puffergo-token-bridge'), $asset_ver);
        }
    }

    private function get_scaffold_style_targets()
    {
        $fallback = array('header' => array('active_callback' => array('PufferGo_Template_Loader', 'get_active_header'), 'asset_file' => 'puffergo-tpl-header-components.css', ), 'footer' => array('active_callback' => array('PufferGo_Template_Loader', 'get_active_footer'), 'asset_file' => 'puffergo-tpl-footer-components.css', ), );
        $categories = $this->load_template_category_manifest();

        if (empty($categories)) {
            return $fallback;
        } $targets = array();

        foreach ($categories as $category) {
            $type_id = isset($category['id']) ? sanitize_key((string) $category['id']) : '';

            if ('' === $type_id || empty($category['isScaffold'])) {
                continue;
            }

if (empty($category['cssScaffold']) || ! is_array($category['cssScaffold'])) {
                continue;
            } $output_file = isset($category['cssScaffold']['outputFile']) ? sanitize_file_name((string) $category['cssScaffold']['outputFile']) : '';

            if ('' === $output_file) {
                continue;
            }

if ('header' === $type_id) {
                $active_callback = array('PufferGo_Template_Loader', 'get_active_header');
            } elseif ('footer' === $type_id) {
                $active_callback = array('PufferGo_Template_Loader', 'get_active_footer');
            } else {
                $active_callback = static function () use ($type_id) { return PufferGo_Template_Loader::get_active_content_template($type_id); };
            } $targets[ $type_id ] = array('active_callback' => $active_callback, 'asset_file' => $output_file, );
        }

return ! empty($targets) ? $targets : $fallback;
    }

    private function load_template_category_manifest()
    {
        static $cached = null;

        if (null !== $cached) {
            return $cached;
        } $path = PUFFERGO_PLUGIN_DIR . '/config/template-category-manifest.json';

        if (! is_readable($path)) {
            puffergo_log('PufferGo: template-category-manifest.json not found; using fallback targets.');
            $cached = array();

            return $cached;
        } $raw = file_get_contents($path);

        if (false === $raw) {
            puffergo_log('PufferGo: template-category-manifest.json unreadable; using fallback targets.');
            $cached = array();

            return $cached;
        } $decoded = json_decode($raw, true);

        if (! is_array($decoded) || empty($decoded['categories']) || ! is_array($decoded['categories'])) {
            puffergo_log('PufferGo: template-category-manifest.json malformed; using fallback targets.');
            $cached = array();

            return $cached;
        } $cached = $decoded['categories'];

        return $cached;
    }

    public function register_api()
    {
        puffergo_log('🔥 PufferGo_AI_Site_Builder: register_api() called');
        register_rest_route('puffergo/v1', '/workflow/profile-default', array('methods' => 'GET', 'callback' => array($this, 'profile_default'), 'permission_callback' => array($this, 'check_permission'), ));
        register_rest_route('puffergo/v1', '/workflow/defaults', array('methods' => 'GET', 'callback' => array($this, 'workflow_defaults'), 'permission_callback' => array($this, 'check_permission'), ));
        register_rest_route('puffergo/v1', '/create-pages', array('methods' => 'POST', 'callback' => array($this, 'create_pages'), 'permission_callback' => array($this, 'check_permission'), ));
        register_rest_route('puffergo/v1', '/publish-pages', array('methods' => 'POST', 'callback' => array($this, 'publish_pages'), 'permission_callback' => array($this, 'check_permission'), ));
        register_rest_route('puffergo/v1', '/apply-scaffold-to-page', array('methods' => 'POST', 'callback' => array($this, 'apply_scaffold_to_page'), 'permission_callback' => array($this, 'check_permission'), ));
        register_rest_route('puffergo/v1', '/workflow/generate-page-content', array('methods' => 'POST', 'callback' => array($this, 'generate_page_content'), 'permission_callback' => array($this, 'check_permission'), ));
    }

    public function check_permission()
    {
        return current_user_can('edit_posts');
    }

    public static function render_admin_page()
    { ?>
        <div class="wrap">
            <div id="puffergo_admin_wrapper" class="puffergo-admin-wrapper"></div>
        </div>
        <?php
    }

    public function enqueue_scripts($hook)
    {
        if ($hook !== 'puffergo_page_puffergo-ai-site-builder') {
            return;
        } wp_enqueue_media();
        $plugin_url = plugin_dir_url(dirname(__FILE__));
        $asset_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-site-builder-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 = time();
        } wp_enqueue_script('puffergo-ai-site-builder', $plugin_url . 'build/blocks/ai-site-builder-app/index.js', $dependencies, $version, true);
        $css_file = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-site-builder-app/index.css';

        if (file_exists($css_file)) {
            wp_enqueue_style('puffergo-ai-site-builder-styles', $plugin_url . 'build/blocks/ai-site-builder-app/index.css', array('puffergo-admin-tailwind'), $version);
        } $style_index_css = plugin_dir_path(dirname(__FILE__)) . 'build/blocks/ai-site-builder-app/style-index.css';

        if (file_exists($style_index_css)) {
            wp_enqueue_style('puffergo-ai-site-builder-style', $plugin_url . 'build/blocks/ai-site-builder-app/style-index.css', array('puffergo-admin-tailwind'), $version);
        } $theme_bridge = new PufferGo_Theme_Bridge();
        wp_localize_script('puffergo-ai-site-builder', 'puffergoAiSiteBuilder', array('restUrl' => rest_url('puffergo/v1/'), 'nonce' => wp_create_nonce('wp_rest'), 'currentUserId' => get_current_user_id(), 'adminUrl' => admin_url(), 'dashboardUrl' => admin_url('admin.php?page=puffergo'), 'hasApiKey' => ! empty(get_option('puffergo_api_key', '')), 'connectUrl' => PUFFERGO_BASE_URL . '/dashboard/connect', 'siteName' => get_bloginfo('name'), 'homeUrl' => home_url(), 'themeCssVars' => $theme_bridge->get_css_variables(), 'quickStyleCss' => PufferGo_Theme_Bridge::get_quick_style_css(), 'coreCssUrl' => plugins_url('assets/css/puffergo.css', PUFFERGO_PLUGIN_FILE), 'locale' => get_user_locale(), 'alpineJsUrl' => plugins_url('assets/js/alpine.min.js', PUFFERGO_PLUGIN_FILE), 'isBlockTheme' => function_exists('wp_is_block_theme') ? wp_is_block_theme() : (bool) file_exists(get_template_directory() . '/theme.json'), 'pageConcurrency' => 2, ));
        PufferGo_Workflow_Jobs_REST::add_poll_config_inline_script('puffergo-ai-site-builder');
        wp_enqueue_style('wp-components');
    }

    public const PROFILE_DEFAULT_TRANSIENT = 'puffergo_profile_default';

    public const WORKFLOW_DEFAULTS_TRANSIENT = 'puffergo_workflow_defaults';

    private function get_default_site_profile()
    {
        $cached = get_transient(self::WORKFLOW_DEFAULTS_TRANSIENT);

        if (is_string($cached)) {
            $decoded = json_decode($cached, true);

            if (! empty($decoded['defaults']['profile']) && is_array($decoded['defaults']['profile'])) {
                return $decoded['defaults']['profile'];
            }
        }

try {
            $data = $this->call_workflow_api_get('/api/workflow/defaults');

            if (! empty($data['defaults']['profile']) && is_array($data['defaults']['profile'])) {
                set_transient(self::WORKFLOW_DEFAULTS_TRANSIENT, wp_json_encode($data), HOUR_IN_SECONDS);

                return $data['defaults']['profile'];
            }
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: get_default_site_profile (defaults) 失败 - ' . $e->getMessage());
        } $cached = get_transient(self::PROFILE_DEFAULT_TRANSIENT);

        if (is_string($cached)) {
            $decoded = json_decode($cached, true);

            if (is_array($decoded)) {
                return $decoded;
            }
        }

try {
            $data = $this->call_workflow_api_get('/api/workflow/profile-default');

            if (! empty($data['defaultProfile']) && is_array($data['defaultProfile'])) {
                set_transient(self::PROFILE_DEFAULT_TRANSIENT, wp_json_encode($data['defaultProfile']), HOUR_IN_SECONDS);

                return $data['defaultProfile'];
            }
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: get_default_site_profile (profile-default) 失败 - ' . $e->getMessage());
        }

return $this->get_fallback_default_site_profile();
    }

    private function get_workflow_defaults()
    {
        $cached = get_transient(self::WORKFLOW_DEFAULTS_TRANSIENT);

        if (is_string($cached)) {
            $decoded = json_decode($cached, true);

            if (! empty($decoded['defaults']) && is_array($decoded['defaults'])) {
                return $decoded;
            }
        }

try {
            $data = $this->call_workflow_api_get('/api/workflow/defaults');

            if (! empty($data['defaults']) && is_array($data['defaults'])) {
                set_transient(self::WORKFLOW_DEFAULTS_TRANSIENT, wp_json_encode($data), HOUR_IN_SECONDS);

                return $data;
            }
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: get_workflow_defaults 失败 - ' . $e->getMessage());
        }

return null;
    }

    private function get_fallback_default_site_profile()
    {
        return array('audience' => array('role' => '', 'priorities' => '', 'regions' => ''), 'identity' => array('brand_name' => '', 'slogan' => '', 'founded' => '', 'story' => ''), 'contact' => array('email' => '', 'phone' => '', 'address' => '', 'channels' => array()), 'business' => array('industry' => '', 'products' => array()), 'advantage' => array('certifications' => array(), 'pillars' => array(), 'pain_points' => '', 'tone' => 'Professional'), 'trustData' => array('employees' => '', 'factoryAreaSqm' => '', 'annualCapacity' => '', 'productionLines' => '', 'passRate' => '', 'servedCountries' => '', 'servedClients' => '', 'avgResponseHours' => '', 'representativeClients' => array(), ), 'testimonials' => array(), 'assets' => array('logo_attachment_id' => 0, 'logo_url' => '', ), 'seo' => array('keywords' => array()), 'special_instructions' => '', );
    }

    private function normalize_profile_for_builder($profile)
    {
        $default = $this->get_default_site_profile();
        $merged = array();

        foreach (array_keys($default) as $block) {
            if ($block === 'special_instructions') {
                $merged[ $block ] = (isset($profile[ $block ]) && is_string($profile[ $block ])) ? sanitize_textarea_field($profile[ $block ]) : $default[ $block ];
                continue;
            } $merged[ $block ] = isset($profile[ $block ]) && is_array($profile[ $block ]) ? array_merge($default[ $block ], $profile[ $block ]) : $default[ $block ];
        }

foreach (array_keys($profile) as $block) {
            if (! array_key_exists($block, $merged)) {
                $merged[ $block ] = $profile[ $block ];
            }
        } $prods = isset($merged['business']['products']) && is_array($merged['business']['products']) ? $merged['business']['products'] : array();
        $merged['business']['products'] = array_slice(array_map(function ($p) {
            $name = is_array($p) && isset($p['name']) ? $p['name'] : (is_string($p) ? $p : '');

            return array('name' => $name);
        }, $prods), 0, 3);

        if (! isset($merged['advantage']['pillars']) || ! is_array($merged['advantage']['pillars'])) {
            $merged['advantage']['pillars'] = array();
        } $kw = isset($merged['seo']['keywords']) ? $merged['seo']['keywords'] : array();
        $merged['seo']['keywords'] = is_array($kw) ? array_slice(array_map('sanitize_text_field', array_filter($kw, 'is_string')), 0, 30) : (is_string($kw) ? array_slice(array_filter(array_map('trim', preg_split('/[\n,]+/', $kw))), 0, 30) : array());

        return $merged;
    }

    public function profile_default($request)
    {
        try {
            $data = $this->call_workflow_api_get('/api/workflow/profile-default');

            return new WP_REST_Response(array('success' => true, 'data' => $data), 200);
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: profile-default 失败 - ' . $e->getMessage());

            return new WP_REST_Response(array('success' => false, 'message' => $e->getMessage(), ), 500);
        }
    }

    public function workflow_defaults($request)
    {
        try {
            $data = $this->call_workflow_api_get('/api/workflow/defaults');

            return new WP_REST_Response(array('success' => true, 'data' => $data), 200);
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: workflow/defaults 失败 - ' . $e->getMessage());

            return new WP_REST_Response(array('success' => false, 'message' => $e->getMessage(), ), 500);
        }
    }

    public function create_pages($request)
    {
        puffergo_log('=== AI Site Builder: Step 5 - 创建页面 ===');
        $start_time = microtime(true);
        $params = $request->get_json_params();
        $pages_data = $params['pages'] ?? array();
        $global_elements = $params['globalElements'] ?? array();
        $structural_pages = $params['structuralPages'] ?? array();

        if (empty($pages_data)) {
            return new WP_REST_Response(array('success' => false, 'message' => __('No page data', 'puffergo'), ), 400);
        } puffergo_ensure_primary_menu();
        puffergo_ensure_footer_menu();
        update_option('puffergo_ai_building', true);
        $results = array();
        $success_count = 0;
        $fail_count = 0;
        $homepage_id = 0;
        $path_to_page_id = array();

        foreach ($pages_data as $page_data) {
            try {
                $site_pages = $params['sitePages'] ?? array();
                $page_id = $this->create_tailwind_page($page_data, $site_pages);

                if ($homepage_id === 0 || (isset($page_data['pageType']) && $page_data['pageType'] === 'HOME_PAGE')) {
                    $homepage_id = $page_id;
                } $raw_path = isset($page_data['path']) ? (string) $page_data['path'] : '';
                $norm_path = '/' . ltrim($raw_path, '/');
                $path_to_page_id[ $norm_path ] = $page_id;
                $results[] = array('success' => true, 'pageId' => $page_id, 'pageName' => $page_data['name'] ?? '', 'editUrl' => admin_url('post.php?post=' . $page_id . '&action=edit'), 'viewUrl' => get_permalink($page_id), 'previewUrl' => get_preview_post_link($page_id), );
                ++$success_count;
                puffergo_log('AI Site Builder: 页面创建成功 - ' . ($page_data['name'] ?? '') . ' (ID: ' . $page_id . ')');
            } catch (\Throwable $e) {
                $results[] = array('success' => false, 'pageName' => $page_data['name'] ?? '', 'error' => $e->getMessage(), );
                ++$fail_count;
                puffergo_log('AI Site Builder: 页面创建失败 - ' . ($page_data['name'] ?? '') . ': ' . $e->getMessage());
            }
        } $site_settings_changed = array();
        $current_front = (int) get_option('page_on_front', 0);
        $current_show = get_option('show_on_front', 'posts');
        $has_existing_homepage = ($current_show === 'page' && $current_front > 0);

        if ($homepage_id > 0) {
            if (class_exists('PufferGo_Homepage_Guard')) {
                PufferGo_Homepage_Guard::mark_as_homepage_candidate($homepage_id);
            }

if ($has_existing_homepage && $current_front !== $homepage_id) {
                $site_settings_changed['homepage_skipped'] = array('message' => __('An existing static front page was detected. PufferGo will not override it. Please manually set the new homepage in Settings → Reading if desired.', 'puffergo'), 'existing_page_id' => $current_front, 'existing_page_title' => get_the_title($current_front), 'new_page_id' => $homepage_id, 'new_page_title' => get_the_title($homepage_id), );
                puffergo_log('Skipped setting page_on_front — existing homepage detected (ID: ' . $current_front . ')');
            } elseif ($current_front !== $homepage_id || $current_show !== 'page') {
                $site_settings_changed['page_on_front'] = array('old' => '未设置（使用博客首页）', 'new' => get_the_title($homepage_id), );
                update_option('page_on_front', $homepage_id);
                update_option('show_on_front', 'page');
                puffergo_log('Set page_on_front to ' . $homepage_id);
            }
        }

if (function_exists('puffergo_ensure_blog_page')) {
            puffergo_ensure_blog_page();
        } $ai_header_items = isset($global_elements['header']['menuItems']) && is_array($global_elements['header']['menuItems']) ? $global_elements['header']['menuItems'] : array();
        $primary_spec = $this->build_primary_menu_spec($ai_header_items, $structural_pages);

        if (! empty($primary_spec)) {
            puffergo_sync_primary_menu($primary_spec);
        } $ai_footer = isset($global_elements['footer']) && is_array($global_elements['footer']) ? $global_elements['footer'] : array();
        $footer_sections = $this->build_footer_sections_spec($ai_footer, $structural_pages);

        if (! empty($footer_sections)) {
            puffergo_rebuild_footer_menu($footer_sections);
        } $duration = microtime(true) - $start_time;
        puffergo_log('AI Site Builder: 批量创建完成，成功: ' . $success_count . '，失败: ' . $fail_count . '，耗时: ' . round($duration, 4) . ' 秒');
        delete_option('puffergo_ai_building');
        $response_data = array('results' => $results, 'summary' => array('mode' => 'tailwind', 'total' => count($pages_data), 'success' => $success_count, 'failed' => $fail_count, ), );

        if (! empty($site_settings_changed)) {
            $response_data['siteSettingsChanged'] = $site_settings_changed;
        }

return new WP_REST_Response(array('success' => true, 'data' => $response_data, ), 200);
    }

    private function build_primary_menu_spec(array $ai_items, array $structural_pages)
    {
        $spec = array();

        foreach ($ai_items as $item) {
            $label = isset($item['name']) ? sanitize_text_field((string) $item['name']) : '';
            $path = isset($item['path']) ? '/' . ltrim((string) $item['path'], '/') : '';

            if ($label === '' || $path === '') {
                continue;
            } $children = array();

            if (! empty($item['children']) && is_array($item['children'])) {
                foreach ($item['children'] as $child) {
                    $child_label = isset($child['name']) ? sanitize_text_field((string) $child['name']) : '';
                    $child_path = isset($child['path']) ? '/' . ltrim((string) $child['path'], '/') : '';

                    if ($child_label === '' || $child_path === '') {
                        continue;
                    } $children[] = array('label' => $child_label, 'url' => home_url($child_path), 'children' => array());
                }
            } $spec[] = array('label' => $label, 'url' => home_url($path), 'children' => $children);
        }

return $spec;
    }

    private function build_footer_sections_spec(array $ai_footer, array $structural_pages)
    {
        $sections = array();
        $covered_paths = array();

        if (! empty($ai_footer['sections']) && is_array($ai_footer['sections'])) {
            foreach ($ai_footer['sections'] as $section) {
                $title = isset($section['title']) ? sanitize_text_field((string) $section['title']) : '';
                $links = array();

                if (! empty($section['links']) && is_array($section['links'])) {
                    foreach ($section['links'] as $link) {
                        $name = isset($link['name']) ? sanitize_text_field((string) $link['name']) : '';
                        $url = isset($link['url']) ? (string) $link['url'] : '';

                        if ($name === '' || $url === '') {
                            continue;
                        } $links[] = array('name' => $name, 'url' => $url);
                        $covered_paths[ puffergo_url_to_path(puffergo_normalize_link_url($url)) ] = true;
                    }
                }

if ($title !== '' && ! empty($links)) {
                    $sections[] = array('title' => $title, 'links' => $links);
                }
            }
        }

return $sections;
    }

    private function create_tailwind_page($page, array $site_pages = array())
    {
        $page_id = 0;
        $page_name = $page['name'] ?? 'Untitled';
        $slug = sanitize_title($page['path'] ?: '');

        if ('' === $slug) {
            if (in_array(mb_strtolower(trim((string) $page_name)), array('home', '首页'), true)) {
                $slug = 'home';
            } else {
                $slug = sanitize_title($page_name);
            }
        } $sections = isset($page['sections']) && is_array($page['sections']) ? $page['sections'] : array();
        puffergo_log('[Phase 2] Creating multi-block page: ' . $page_name);
        puffergo_log('[Phase 2] Sections: ' . count($sections));
        $content = '';

        foreach ($sections as $index => $section) {
            $s_html = $section['html'] ?? '';
            $s_css = $section['css'] ?? '';
            $s_scope_id = $section['scopeId'] ?? '';

            if (empty($s_html) || empty($s_scope_id)) {
                continue;
            } $s_config = array('configTemplate' => $section['configTemplate'] ?? null, 'configSchema' => $section['configSchema'] ?? null, 'configData' => $section['configData'] ?? null, 'editing' => $section['editing'] ?? null, 'blockStyle' => $section['blockStyle'] ?? null, );
            puffergo_log('[Phase 2] Section ' . ($index + 1) . ': scopeId=' . $s_scope_id . ' (' . strlen($s_html) . ' chars)');
            $content .= $this->create_tailwind_block_content($s_html, $s_css, $s_scope_id, $s_config);
            $content .= "\n\n";
        }

if ('' === trim($content)) {
            puffergo_log('[Phase 2] Invalid Step4 payload: sections missing or empty for page: ' . $page_name);

            throw new Exception(esc_html__('Failed to create page: generated content is empty.', 'puffergo'));
        } $reuse_query = array('post_type' => 'page', 'post_status' => 'any', 'name' => $slug, 'posts_per_page' => 1, 'no_found_rows' => true, );
        $default_lang = PufferGo_Polylang::default_language();

        if ('' !== $default_lang) {
            $reuse_query['lang'] = $default_lang;
        } $existing = get_posts($reuse_query);

        if (! empty($existing)) {
            $existing_id = (int) $existing[0]->ID;
            $is_managed = get_post_meta($existing_id, '_puffergo_managed', true);

            if ($is_managed) {
                puffergo_log('[Phase 2] Slug "' . $slug . '" already exists (PufferGo-managed, ID: ' . $existing_id . '), updating content (reset to draft)');
                $updated = wp_update_post(array('ID' => $existing_id, 'post_title' => $page_name, 'post_content' => wp_slash($content), 'post_status' => 'draft', ), true);

                if (is_wp_error($updated)) {
                    throw new Exception($updated->get_error_message());
                } $page_id = $existing_id;
                delete_post_meta($existing_id, '_puffergo_sample_data');
            } else {
                puffergo_log('[Phase 2] Slug "' . $slug . '" exists (user page ID: ' . $existing_id . '), letting WP append suffix');
            }
        }

if (0 === $page_id) {
            $page_id = wp_insert_post(['post_type' => 'page', 'post_title' => $page_name, 'post_name' => $slug, 'post_content' => wp_slash($content), 'post_status' => 'draft', 'post_author' => get_current_user_id(), ], true);

            if (is_wp_error($page_id)) {
                throw new Exception($page_id->get_error_message());
            } puffergo_log('[Phase 2] Page created successfully with ID: ' . $page_id);
        } update_post_meta($page_id, '_wp_page_template', 'puffergo-fullpage.php');
        update_post_meta($page_id, '_puffergo_managed', true);
        PufferGo_Polylang::set_post_language($page_id, PufferGo_Polylang::default_language());
        $seo = isset($page['seo']) && is_array($page['seo']) ? $page['seo'] : array();
        $this->save_seo_meta_for_page($page_id, $seo);

        return $page_id;
    }

    private function save_seo_meta_for_page($page_id, $seo)
    {
        if (empty($seo) || ! is_array($seo)) {
            return;
        } $title = isset($seo['title']) && is_string($seo['title']) ? sanitize_text_field(wp_unslash($seo['title'])) : '';
        $description = isset($seo['description']) && is_string($seo['description']) ? sanitize_textarea_field(wp_unslash($seo['description'])) : '';
        $core = isset($seo['coreKeywords']) && is_array($seo['coreKeywords']) ? array_slice(array_map('sanitize_text_field', array_map('wp_unslash', $seo['coreKeywords'])), 0, 1) : array();
        $long_tail = isset($seo['longTailKeywords']) && is_array($seo['longTailKeywords']) ? array_slice(array_map('sanitize_text_field', array_map('wp_unslash', $seo['longTailKeywords'])), 0, 5) : array();
        $keywords = array_filter(array_merge($core, $long_tail));
        $focus_keyword_string = implode(', ', $keywords);

        if ('' !== $title) {
            update_post_meta($page_id, 'rank_math_title', $title);
            update_post_meta($page_id, '_yoast_wpseo_title', $title);
        }

if ('' !== $description) {
            update_post_meta($page_id, 'rank_math_description', $description);
            update_post_meta($page_id, '_yoast_wpseo_metadesc', $description);
        }

if ('' !== $focus_keyword_string) {
            update_post_meta($page_id, 'rank_math_focus_keyword', $focus_keyword_string);
            update_post_meta($page_id, '_yoast_wpseo_focuskw', $focus_keyword_string);
        }
    }

    private function split_html_into_sections($html)
    {
        if (empty($html)) {
            return array();
        } $sections = array();
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $html_with_meta = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>';
        $dom->loadHTML($html_with_meta, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
        libxml_clear_errors();
        $body = $dom->getElementsByTagName('body')->item(0);

        if (!$body) {
            return array(array('name' => 'Main Content', 'html' => $html, ));
        } $target_node = $body;
        $element_children = array();

        foreach ($body->childNodes as $child) {
            if ($child->nodeType === XML_ELEMENT_NODE) {
                $element_children[] = $child;
            }
        }

if (count($element_children) === 1) {
            $wrapper = $element_children[0];
            $wrapper_tag = strtolower($wrapper->nodeName);
            puffergo_log('[Phase 2] Found single wrapper: <' . $wrapper_tag . '>');

            if (in_array($wrapper_tag, array('div', 'main'), true)) {
                puffergo_log('[Phase 2] Unwrapping <' . $wrapper_tag . '>, using its children instead');
                $target_node = $wrapper;
            }
        } $section_tags = array('header', 'nav', 'main', 'section', 'article', 'aside', 'footer');
        $section_count = array();

        foreach ($target_node->childNodes as $node) {
            if ($node->nodeType !== XML_ELEMENT_NODE) {
                continue;
            } $tag_name = strtolower($node->nodeName);

            if (in_array($tag_name, $section_tags, true)) {
                $section_name = $this->get_section_name($node, $section_count);
                $section_html = $dom->saveHTML($node);
                $sections[] = array('name' => $section_name, 'html' => $section_html, 'tag' => $tag_name, );
            } else {
                $section_html = $dom->saveHTML($node);
                $sections[] = array('name' => 'Content Section', 'html' => $section_html, 'tag' => $tag_name, );
            }
        }

if (empty($sections)) {
            $sections[] = array('name' => 'Main Content', 'html' => $html, 'tag' => 'div', );
        }

return $sections;
    }

    private function get_section_name($node, &$section_count)
    {
        $tag_name = strtolower($node->nodeName);

        if (!isset($section_count[$tag_name])) {
            $section_count[$tag_name] = 0;
        } $section_count[$tag_name]++;
        $name = null;

        if ($node->hasAttribute('id')) {
            $id = $node->getAttribute('id');
            $name = ucwords(str_replace(array('-', '_'), ' ', $id));
        }

if (!$name && $node->hasAttribute('class')) {
            $classes = explode(' ', $node->getAttribute('class'));

            foreach ($classes as $class) {
                if (preg_match('/(hero|cta|feature|about|contact|footer|header|pricing|testimonial|faq)/i', $class, $matches)) {
                    $name = ucfirst($matches[1]);
                    break;
                }
            }
        }

if (!$name) {
            $name = ucfirst($tag_name);

            if ($section_count[$tag_name] > 1) {
                $name .= ' ' . $section_count[$tag_name];
            }
        }

return $name;
    }

    private function rewrite_css_scope_for_section($css, $base_scope_id, $section_scope_id)
    {
        if (empty($base_scope_id) || empty($css)) {
            return $css;
        } $pattern = '/\.' . preg_quote($base_scope_id, '/') . '(?!-)(?=[\s.:\[,\{\}\)])/';

        return preg_replace($pattern, '.' . $section_scope_id, $css);
    }

    private function create_tailwind_block_content($html, $css, $scope_id, array $config = array())
    {
        return PufferGo_Tailwind_Block::serialize((string) $html, (string) $css, (string) $scope_id, $config);
    }

    public function publish_pages($request)
    {
        $params = $request->get_json_params();
        $page_ids = $params['pageIds'] ?? array();

        if (empty($page_ids)) {
            return new WP_REST_Response(['success' => false, 'message' => __('No pages specified for publishing', 'puffergo')], 400);
        } $results = array();
        $success_count = 0;

        foreach ($page_ids as $page_id) {
            $result = wp_update_post(array('ID' => $page_id, 'post_status' => 'publish'), true);

            if (!is_wp_error($result)) {
                $results[] = array('success' => true, 'pageId' => $page_id);
                $success_count++;
            } else {
                $results[] = array('success' => false, 'pageId' => $page_id, 'error' => $result->get_error_message());
            }
        }

return new WP_REST_Response(['success' => true, 'data' => array('results' => $results, 'successCount' => $success_count, )], 200);
    }

    public function apply_scaffold_to_page($request)
    {
        $params = $request->get_json_params();
        $page_id = isset($params['pageId']) ? (int) $params['pageId'] : 0;

        if ($page_id <= 0) {
            $page_id = (int) get_option('page_on_front', 0);
        }

if ($page_id <= 0 || get_post_type($page_id) !== 'page') {
            return new WP_REST_Response(array('success' => false, 'message' => __('Invalid page ID', 'puffergo')), 400);
        } update_post_meta($page_id, '_wp_page_template', 'puffergo-fullpage.php');
        puffergo_log('apply-scaffold-to-page: applied puffergo-fullpage.php to page ID ' . $page_id);

        return new WP_REST_Response(array('success' => true, 'data' => array('pageId' => $page_id, 'pageTitle' => get_the_title($page_id), 'viewUrl' => get_permalink($page_id), ), ), 200);
    }

    private function call_workflow_api($endpoint, $data)
    {
        $api_client = PufferGo_API_Client::get_instance();

        try {
            return $api_client->post($endpoint, $data, array('timeout' => 205, 'log_prefix' => 'AI Site Builder'));
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: API调用失败 - ' . $e->getMessage());

            throw $e;
        }
    }

    private function call_workflow_api_get($endpoint)
    {
        $api_client = PufferGo_API_Client::get_instance();

        try {
            return $api_client->get($endpoint, array(), array('timeout' => 30, 'log_prefix' => 'AI Site Builder'));
        } catch (Exception $e) {
            puffergo_log('AI Site Builder: GET API 失败 - ' . $e->getMessage());

            throw $e;
        }
    }
}
