import { request, AzureOpenAIPatameters, StabilityOption, StabilityResult } from "./declare";
import GptBase from "./gptbase"
export default class StabilityAI extends GptBase {
    
    protected readonly apiKey: string;
    protected readonly apiSetting: AzureOpenAIPatameters
    protected readonly apiOption:StabilityOption;
    /**
     * 
     * @param apiKey 调用OpenAI 的key
     * @param azureOption  用作accesstoken的缓存 
     * @param apiOption  用作accesstoken的缓存 
     */
    constructor(apiKey: string, urlOption: AzureOpenAIPatameters, apiOption: StabilityOption = {}) {
        super();
        this.apiKey = apiKey;
        this.apiSetting = urlOption;
        this.apiOption = apiOption;
        if (!this.apiSetting.endpoint.toLowerCase().startsWith('http')) {
            this.apiSetting.endpoint = 'https://' + this.apiSetting.endpoint;
        }
    }
    /**
     * 请求Stable作画的接口
     */
    public async chatRequest(chatText: string, paramOption: StabilityOption, axiosOption: any = {}): Promise<StabilityResult> {
        if (!chatText) return { successed: false, error: { errcode: 2, errmsg: '缺失聊天的内容' } };
        axiosOption = Object.assign({}, axiosOption,{
            headers:{
                "Content-Type": "application/json",
                "Accept": "application/json",
                "Authorization": `Bearer ${this.apiKey}`
            }
        })
        try {
            let param = {
                ...axiosOption,
                method: "post",
                url: `${this.apiSetting.endpoint}/v1/generation/${this.apiSetting.engine}/text-to-image`,
                data: {
                    text_prompts: [
                        {
                            text: chatText
                        }
                    ],
                    cfg_scale: paramOption.cfg_scale || this.apiOption.cfg_scale || 7,
                    clip_guidance_preset: paramOption.clip_guidance_preset || this.apiOption.clip_guidance_preset || "FAST_BLUE",
                    height: paramOption.height || this.apiOption.height || 512,
                    width: paramOption.width || this.apiOption.width || 512,
                    samples: paramOption.samples || this.apiOption.samples || 1,
                    steps: paramOption.steps || this.apiOption.steps || 30,
                },
                
            };
            const response:any = await request(param)
            if (response.successed) {
                let data = response.data;
                return { successed: true, type: 'image', data: data.artifacts, };
            }
            return { successed: false, ...response.data };
        } catch (error) {
            console.log('result is error ', error)
            return { successed: false, error };
        }

    }
}
