<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Chat_REST
{
    public const UPSTREAM_TIMEOUT_SECONDS = 90;

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

    public function register_routes()
    {
        register_rest_route('puffergo/v1', '/chat/(?P<scene>[a-z0-9-]+)', array('methods' => 'POST', 'callback' => array($this, 'handle_chat'), 'permission_callback' => array($this, 'check_permission'), ));
    }

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

    public function handle_chat($request)
    {
        $scene = isset($request['scene']) ? sanitize_key($request['scene']) : '';

        if ('' === $scene) {
            return new WP_REST_Response(array('success' => false, 'message' => __('Missing scene parameter.', 'puffergo'), ), 400);
        } $params = $request->get_json_params();

        if (! is_array($params)) {
            $params = array();
        } $messages = isset($params['messages']) && is_array($params['messages']) ? $params['messages'] : array();

        if (empty($messages)) {
            return new WP_REST_Response(array('success' => false, 'message' => __('messages is required.', 'puffergo'), ), 400);
        } $messages = array_slice($messages, -40);
        $body = array('messages' => $messages, 'context' => isset($params['context']) && is_array($params['context']) ? $params['context'] : array(), 'language' => isset($params['language']) ? sanitize_text_field(wp_unslash((string) $params['language'])) : 'zh_CN', );

        if (isset($params['model']) && is_string($params['model'])) {
            $body['model'] = sanitize_text_field(wp_unslash($params['model']));
        }

if (isset($params['aiScene']) && is_string($params['aiScene'])) {
            $body['aiScene'] = sanitize_text_field(wp_unslash($params['aiScene']));
        } elseif ('site-profile' === $scene) {
            $body['aiScene'] = 'site_build.copilot_chat';
        }

try {
            $api = PufferGo_API_Client::get_instance();
            $result = $api->post('/api/chat/' . rawurlencode($scene), $body, array('timeout' => self::UPSTREAM_TIMEOUT_SECONDS, 'log_prefix' => 'Chat ' . $scene, 'success_http_codes' => array(200), 'return_raw_result' => true, ));

            return new WP_REST_Response($result, 200);
        } catch (PufferGo_API_Exception $e) {
            return new WP_REST_Response($e->toArray(), $e->getCode());
        } catch (Exception $e) {
            return new WP_REST_Response(array('success' => false, 'message' => $e->getMessage(), ), 500);
        }
    }
}
