<?php
/**
 * PufferGo 品牌设计系统管理
 *
 * 职责：
 * 1. 存储/读取 AI 生成的多套品牌设计方案（WordPress Option）
 * 2. 提供 REST API 供前端 CRUD
 * 3. 提供静态方法供 Theme Bridge 读取当前激活方案
 *
 * 站点相关信息（品牌名、行业、受众等）统一存 puffergo_site_profile，此处仅存设计系统数据。
 *
 * Option 结构（puffergo_design_system）：
 * {
 *   schemes:       Array<Scheme>,   // 所有方案
 *   activeSchemeId: string,         // 当前激活方案 ID
 *   updatedAt:     string,
 * }
 *
 * @package PufferGo_Core
 * @since   2.2.0
 */

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

class PufferGo_Design_System {

    const OPTION_KEY = 'puffergo_design_system';

    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
    }

    /**
     * 注册 REST 路由
     */
    public function register_rest_routes() {
        register_rest_route(
            'puffergo/v1',
            '/design-system',
            array(
                array(
                    'methods'             => 'GET',
                    'callback'            => array( $this, 'rest_get' ),
                    'permission_callback' => function () {
                        return current_user_can( 'edit_posts' );
                    },
                ),
                array(
                    'methods'             => 'PUT',
                    'callback'            => array( $this, 'rest_save' ),
                    'permission_callback' => function () {
                        return current_user_can( 'edit_posts' );
                    },
                ),
            )
        );

        // 专用端点：用 AI 生成 3 套品牌设计 token 方案并自动入库
        register_rest_route(
            'puffergo/v1',
            '/design-system/generate',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'rest_generate' ),
                'permission_callback' => function () {
                    return current_user_can( 'edit_posts' );
                },
            )
        );
    }

    /**
     * POST /puffergo/v1/design-system/generate
     *
     * 调用 AI 生成 3 套品牌设计 token 方案，自动持久化并返回。
     *
     * 请求体：
     * {
     *   brandContext: { name, industry, products, audience, tone } 由前端从 puffergo_site_profile 派生，
     *   userHint:     string|null,
     *   model:        string
     * }
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function rest_generate( $request ) {
        $params        = $request->get_json_params();
        $model         = isset( $params['model'] )    ? sanitize_text_field( wp_unslash( $params['model'] ) )        : 'deepseek-v3';
        $hint          = isset( $params['userHint'] ) ? sanitize_textarea_field( wp_unslash( $params['userHint'] ) ) : '';
        $bc_raw        = isset( $params['brandContext'] ) && is_array( $params['brandContext'] ) ? $params['brandContext'] : array();

        $brand_context = array(
            'name'     => sanitize_text_field( $bc_raw['name']     ?? '' ),
            'industry' => sanitize_text_field( $bc_raw['industry'] ?? '' ),
            'products' => sanitize_text_field( $bc_raw['products'] ?? '' ),
            'audience' => sanitize_text_field( $bc_raw['audience'] ?? '' ),
            'tone'     => sanitize_text_field( $bc_raw['tone']     ?? '' ),
        );

        try {
            // prompt 构建和 AI 调用由后端 Node.js /api/ai/generate-design-tokens 负责
            $client = PufferGo_API_Client::get_instance();
            $result = $client->post(
                '/api/ai/generate-design-tokens',
                array(
                    'brandContext' => $brand_context,
                    'userHint'     => $hint ?: null,
                    'model'        => $model,
                ),
                array( 'timeout' => 120, 'log_prefix' => 'DesignSystem Generate' )
            );

            // API Client 已将 response.data 解包，$result 直接是 { schemes: [...] }
            $raw_schemes = isset( $result['schemes'] ) && is_array( $result['schemes'] )
                ? $result['schemes']
                : array();

            if ( empty( $raw_schemes ) ) {
                return new WP_REST_Response( array(
                    'success' => false,
                    'message' => esc_html__( 'AI 未返回设计方案，请重试', 'puffergo' ),
                ), 500 );
            }

            // 追加 id / generatedAt / isCustom，并做安全过滤
            $ts          = round( microtime( true ) * 1000 );
            $new_schemes = array();
            foreach ( $raw_schemes as $i => $s ) {
                $new_schemes[] = $this->sanitize_scheme( array_merge(
                    $s,
                    array(
                        'id'          => 'scheme_' . $ts . '_' . $i,
                        'generatedAt' => gmdate( 'c' ),
                        'isCustom'    => false,
                    )
                ) );
            }

            $new_active_id = $new_schemes[0]['id'];

            $data = array(
                'schemes'        => $new_schemes,
                'activeSchemeId' => $new_active_id,
                'updatedAt'      => current_time( 'c' ),
            );

            // 从激活方案的 tokens.compiledCss 读取（Node.js 已为所有方案预编译）
            $active_compiled = isset( $new_schemes[0]['tokens']['compiledCss'] ) ? $new_schemes[0]['tokens']['compiledCss'] : '';
            if ( ! empty( $active_compiled ) ) {
                $data['compiledCss'] = $active_compiled;
            }

            update_option( self::OPTION_KEY, $data, false );

            return new WP_REST_Response( array(
                'success' => true,
                'data'    => array(
                    'schemes'        => $new_schemes,
                    'activeSchemeId' => $new_active_id,
                ),
            ), 200 );

        } catch ( PufferGo_API_Exception $e ) {
            puffergo_log( '[DesignSystem Generate] API Exception: ' . $e->getMessage() );
            return new WP_REST_Response( $e->toArray(), $e->getCode() );
        } catch ( Exception $e ) {
            puffergo_log( '[DesignSystem Generate] Error: ' . $e->getMessage() );
            return new WP_REST_Response( array(
                'success' => false,
                'message' => $e->getMessage(),
            ), 500 );
        }
    }

    /**
     * GET /puffergo/v1/design-system
     *
     * 仅返回 schemes、activeSchemeId、updatedAt（不包含站点信息，站点信息在 puffergo_site_profile）。
     *
     * @return WP_REST_Response
     */
    public function rest_get( $request ) {
        $raw  = get_option( self::OPTION_KEY, null );
        $schemes = isset( $raw['schemes'] ) ? $raw['schemes'] : array();

        $data = is_array( $raw ) ? array(
            'schemes'        => $schemes,
            'activeSchemeId' => isset( $raw['activeSchemeId'] ) ? $raw['activeSchemeId'] : '',
            'updatedAt'      => isset( $raw['updatedAt'] ) ? $raw['updatedAt'] : '',
        ) : array( 'schemes' => array(), 'activeSchemeId' => '', 'updatedAt' => '' );

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

    /**
     * PUT /puffergo/v1/design-system
     *
     * 接受 schemes + activeSchemeId 并覆盖保存（不存站点信息）。
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function rest_save( $request ) {
        $params    = $request->get_json_params();
        $schemes   = isset( $params['schemes'] ) ? $params['schemes'] : array();
        $active_id = isset( $params['activeSchemeId'] ) ? sanitize_text_field( wp_unslash( $params['activeSchemeId'] ) ) : '';

        $sanitized_schemes = array();
        foreach ( $schemes as $scheme ) {
            $sanitized_schemes[] = $this->sanitize_scheme( $scheme );
        }

        $data = array(
            'schemes'        => $sanitized_schemes,
            'activeSchemeId' => $active_id,
            'updatedAt'      => current_time( 'c' ),
        );

        // 从激活方案的 tokens.compiledCss 读取（Node.js 已在生成时预编译）
        foreach ( $sanitized_schemes as $scheme ) {
            if ( isset( $scheme['id'] ) && $scheme['id'] === $active_id ) {
                $compiled = isset( $scheme['tokens']['compiledCss'] ) ? $scheme['tokens']['compiledCss'] : '';
                if ( ! empty( $compiled ) ) {
                    $data['compiledCss'] = $compiled;
                }
                break;
            }
        }

        update_option( self::OPTION_KEY, $data, false );

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

    /**
     * 清洗单个方案数据（6-token 结构）
     *
     * AI 返回 6 个 token：primaryColor, secondaryColor, baseColor, borderRadius, fontHeading, fontBody
     * 色阶（brand-50~950, accent-50~950, neutral-50~950）由 Node.js 编译为 CSS 变量，PHP 不计算。
     *
     * @param array $scheme 原始方案数据
     * @return array        清洗后的方案数据
     */
    private function sanitize_scheme( $scheme ) {
        $allowed_radii = array( '0px', '2px', '4px', '6px', '8px', '12px', '16px', '9999px' );

        $allowed_fonts = array_merge(
            array_keys( PufferGo_Theme_Bridge::GOOGLE_FONTS_MAP ),
            array( 'sans-serif', 'serif', 'monospace', 'system-ui', 'Arial', 'Helvetica', 'Georgia', 'Times New Roman' )
        );

        $t = isset( $scheme['tokens'] ) && is_array( $scheme['tokens'] ) ? $scheme['tokens'] : array();

        $primary   = sanitize_hex_color( $t['primaryColor']   ?? '' ) ?: '#3b82f6';
        $secondary = sanitize_hex_color( $t['secondaryColor'] ?? '' ) ?: '#f59e0b';
        $base      = sanitize_hex_color( $t['baseColor']      ?? '' ) ?: '#ffffff';

        $raw_radius = isset( $t['borderRadius'] ) ? sanitize_text_field( $t['borderRadius'] ) : '8px';
        $radius     = in_array( $raw_radius, $allowed_radii, true ) ? $raw_radius : '8px';

        $raw_heading  = isset( $t['fontHeading'] ) ? sanitize_text_field( $t['fontHeading'] ) : 'sans-serif';
        $raw_body     = isset( $t['fontBody'] )    ? sanitize_text_field( $t['fontBody'] )    : 'sans-serif';
        $font_heading = in_array( $raw_heading, $allowed_fonts, true ) ? $raw_heading : 'sans-serif';
        $font_body    = in_array( $raw_body, $allowed_fonts, true )    ? $raw_body : 'sans-serif';

        return array(
            'id'          => sanitize_text_field( $scheme['id']          ?? '' ),
            'name'        => sanitize_text_field( $scheme['name']        ?? '' ),
            'rationale'   => sanitize_textarea_field( $scheme['rationale']   ?? '' ),
            'generatedAt' => sanitize_text_field( $scheme['generatedAt'] ?? '' ),
            'isCustom'    => (bool) ( $scheme['isCustom'] ?? false ),
            'tokens'      => array(
                'primaryColor'   => $primary,
                'secondaryColor' => $secondary,
                'baseColor'      => $base,
                'borderRadius'   => $radius,
                'fontHeading'    => $font_heading,
                'fontBody'       => $font_body,
                'compiledCss'    => isset( $t['compiledCss'] ) ? $t['compiledCss'] : '',
            ),
        );
    }

    /**
     * 获取当前激活方案的 tokens（供 Theme Bridge 静态调用）
     *
     * @return array|null tokens 数组，或 null（未设置时）
     */
    public static function get_active_tokens() {
        $data = get_option( self::OPTION_KEY, null );

        if ( ! $data || ! is_array( $data ) || empty( $data['schemes'] ) || ! is_array( $data['schemes'] ) ) {
            return null;
        }

        $active_id = isset( $data['activeSchemeId'] ) ? (string) $data['activeSchemeId'] : '';
        if ( '' === $active_id ) {
            return null;
        }

        foreach ( $data['schemes'] as $scheme ) {
            if ( isset( $scheme['id'] ) && $scheme['id'] === $active_id ) {
                return isset( $scheme['tokens'] ) ? $scheme['tokens'] : null;
            }
        }

        return null;
    }

    /**
     * 获取 Node.js 预编译的 CSS 变量字符串
     *
     * @return string|null
     */
    public static function get_compiled_css() {
        $data = get_option( self::OPTION_KEY, null );
        if ( ! $data || ! is_array( $data ) ) {
            return null;
        }
        // 优先从激活方案的 tokens.compiledCss 读取
        $active_id = isset( $data['activeSchemeId'] ) ? (string) $data['activeSchemeId'] : '';
        if ( '' !== $active_id && ! empty( $data['schemes'] ) ) {
            foreach ( $data['schemes'] as $scheme ) {
                if ( isset( $scheme['id'] ) && $scheme['id'] === $active_id ) {
                    $compiled = isset( $scheme['tokens']['compiledCss'] ) ? $scheme['tokens']['compiledCss'] : '';
                    if ( ! empty( $compiled ) ) {
                        return $compiled;
                    }
                    break;
                }
            }
        }
        // Fallback: top-level compiledCss（旧数据兼容）
        return isset( $data['compiledCss'] ) ? $data['compiledCss'] : null;
    }

}

new PufferGo_Design_System();
