<?php

/**
 * Copyright 1999-2022 iFLYTEK Corporation
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace IFlytek\Xfyun\Speech;

use IFlytek\Xfyun\Core\Traits\SignTrait;
use IFlytek\Xfyun\Core\HttpClient;
/**
 * 讯飞Ai户端
 *
 * @author guizheng@iflytek.com
 */
class ChatClient
{
    use SignTrait;

    protected $appId;
    protected $apiKey;
    protected $apiSecret;
    protected $uid;
    protected $resId;
    protected $requestConfig;
    protected $client;

    public function __construct($appId, $apiKey, $apiSecret, $uid = null, $resId = null, $requestConfig = [])
    {
        $this->appId = $appId;
        $this->apiKey = $apiKey;
        $this->apiSecret = $apiSecret;
        $this->uid = $uid;
        $this->resId = $resId;
        $this->client = new HttpClient([]);
    }

    function assembleAuthUrl($addr,$method='GET') {
        $apiKey=$this->apiKey;
        $apiSecret=$this->apiSecret;
        if ($apiKey == "" && $apiSecret == "") { // 不鉴权
            return $addr;
        }
        
        $ul = parse_url($addr); // 解析地址
        if ($ul === false) { // 地址不对,也不鉴权
            return $addr;
        }
        // // $date = date(DATE_RFC1123); // 获取当前时间并格式化为RFC1123格式的字符串
        $timestamp = time();
        $rfc1123_format = gmdate("D, d M Y H:i:s \G\M\T", $timestamp);
        // $rfc1123_format = "Mon, 31 Jul 2023 08:24:03 GMT";
        // 参与签名的字段 host, date, request-line
        $signString = array("host: " . $ul["host"], "date: " . $rfc1123_format, $method . " " . $ul["path"] . " HTTP/1.1");
        // 对签名字符串进行排序,确保顺序一致
        // ksort($signString);
        // 将签名字符串拼接成一个字符串
        $sgin = implode("\n", $signString);
        // 对签名字符串进行HMAC-SHA256加密,得到签名结果
        $sha = hash_hmac('sha256', $sgin, $apiSecret,true);
        
        $signature_sha_base64 = base64_encode($sha);
        
        // 将API密钥、算法、头部信息和签名结果拼接成一个授权URL
        $authUrl = "api_key=\"$apiKey\",algorithm=\"hmac-sha256\",headers=\"host date request-line\",signature=\"$signature_sha_base64\"";
        // 对授权URL进行Base64编码,并添加到原始地址后面作为查询参数
        $authAddr = $addr . '?' . http_build_query(array(
            'host' => $ul['host'],
            'date' => $rfc1123_format,
            'authorization' => base64_encode($authUrl),
        ));
        return $authAddr;
    }

    function getBody($appid, $question)
    {
        $header = array(
            "app_id" => $appid,
            "uid" => "1"
        );

        $parameter = array(
            "chat" => array(
                "domain" => "generalv2",
                "temperature" => 0.5,
                "max_tokens" => 1024
            )
        );

        $payload = array(
            "message" => array(
                "text" => array(
                    array("role" => "user", "content" => $question)
                )
            )
        );

        $json_string = json_encode(array(
            "header" => $header,
            "parameter" => $parameter,
            "payload" => $payload
        ));

        return $json_string;
    }

}