//
//
//  BaiduAgentApi.m
//  ChatAgentApp
//
//  Created by Sun,Jian(ACU-T102) on 2018/12/31.
//  Copyright © 2018年 Sun,Jian(ACU-T102). All rights reserved.
//

#import "BaiduAgentApi.h"
#import <UIKit/UIKit.h>


#define SERVER_HOST_ONLINE         @"https://ai.agent.kaywang.cn"
#define START_CALL_PATH_ONLINE     @"/api/v1/aiagent/generateAIAgentCall"
#define STOP_CALL_PATH_ONLINE      @"/api/v1/aiagent/stopAIAgentInstance"

#define SERVER_HOST                @"http://182.61.62.159:8988"
#define START_CALL_PATH            @"/internal/v1/aiagent/generateAIAgentCall"
#define STOP_CALL_PATH             @"/internal/v1/aiagent/stopAIAgentInstance"

#define SERVER_HOST_DH                @"https://ai.agent.kaywang.cn"
#define START_CALL_PATH_DH            @"/dh/v1/aiagent/generateAIAgentCall"
#define STOP_CALL_PATH_DH             @"/dh/v1/aiagent/stopAIAgentInstance"

NSString *g_evn = @"";

@interface BaiduAgentApi ()
@property (nonatomic, copy) NSString *Server_host_env;
@property (nonatomic, copy) NSString *Server_path_start;
@property (nonatomic, copy) NSString *Server_path_stop;
@property (nonatomic, copy) NSString *Conf;
@property (nonatomic, weak) id<BaiduAgentApiEventDelegate> delegate;

@end

@implementation BaiduAgentApi
#ifndef APP_FOR_TAL
//  "config" : "{\"llm\":\"LLM4T\",\"llm_token\":\"no\",\"tts_sayhi\":\"welcome-welcome nihao\"}",
+ (NSString *) configBuild:(NSString *)env model:(NSString *)model tts:(NSString *)tts asr:(NSString *)asr  {

    g_evn = env;
    NSString *jsonString = @"";
    NSDictionary *jsonDict = @{
        @"llm" : model,
        @"llm_token" : @"no",
        @"lang" : tts,
//        @"tts_sayhi" : @"有什么英语的问题可以随时问我",
//        @"role":@"你是一位经验丰富的英语外教，性格活泼开朗，英语口语纯正，擅长用生动有趣的方式教授英语知识，如词汇、语法、口语表达等。在交流中善于引导学生开口说英语，纠正发音和语法错误，还能分享国外的文化习俗，营造沉浸式的英语学习氛围",
    };
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"Error Create Json: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return  jsonString;
}
#else
+ (NSString *) configBuild:(NSString *)env model:(NSString *)model llmurl:(NSString *)llm_url tts:(NSString *)ttsSay  {
    g_evn = env;
    NSString *jsonString = @"";
    NSDictionary *jsonDict = @{
        @"llm" : model,
        @"llm_url" :llm_url,
        @"tts_sayhi" : ttsSay
        
    };
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"Error Create Json: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return  jsonString;
}
#endif
- (instancetype)initWithParams:(NSString *)config delegate:(id<BaiduAgentApiEventDelegate>)delegate{
    if (self = [super init]) {
        if ([g_evn  isEqual: @"test"]) {
            self.Server_host_env = SERVER_HOST;
            self.Server_path_start = START_CALL_PATH;
            self.Server_path_stop = STOP_CALL_PATH;
        } else if ([g_evn isEqual:@"online"]){
            self.Server_host_env = SERVER_HOST_ONLINE;
            self.Server_path_start = START_CALL_PATH_ONLINE;
            self.Server_path_stop = STOP_CALL_PATH_ONLINE;
        } else {
            self.Server_host_env = SERVER_HOST_DH;
            self.Server_path_start = START_CALL_PATH_DH;
            self.Server_path_stop = STOP_CALL_PATH_DH;
        }
        self.Conf = config;
        self.delegate = delegate;
    }
    return self;
}
- (void) sendStartRequest:(BaiduAgentApiStartRequest *) params block:(void (^)(BaiduAgentApiStartResponse *))block {
    if (params == nil || [params.appId length] <= 0) {
        return;
    }

    NSString * url = [NSString stringWithFormat:@"%@%@", self.Server_host_env, self.Server_path_start];
    NSURL* urlRequest = [NSURL URLWithString:url];

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];

    NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
    [dict setValue:params.appId forKey:@"app_id"];
    [dict setValue:@(params.quicStart) forKey:@"quick_start"];
    if (params.config && [params.config length] > 0) {
        [dict setValue:params.config forKey:@"config"];
    }

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"[AgentApi][REQ] url %@, body: %@", urlRequest, jsonStr);

    request.HTTPBody = jsonData;
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:request
                   completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSDictionary *resposneDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"[AgentApi][RESP] url %@, statusCode:%ld, response: %@", urlRequest, [httpResponse statusCode], resposneDict);
        if ([httpResponse statusCode] != 200) {
            [self.delegate  BaiduAgentApiConnectFailed];
            return;
        }
        if (error) {
            NSLog(@"sendStartRequest fail, error: %@", error.description);
            return;
        }
        [self handleSendStartRequest:data block:block];

    }] resume];
}

- (void)sendStopRequest:(BaiduAgentApiStopRequest *)params block:(void (^)(BaiduAgentApiStopResponse *))block {
    if (params == nil || [params.appId length] <= 0) {
        return;
    }
    
    NSString * url = [NSString stringWithFormat:@"%@%@", SERVER_HOST, STOP_CALL_PATH];
    NSURL* urlRequest = [NSURL URLWithString:url];

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:urlRequest];

    NSMutableDictionary *dict  = [[NSMutableDictionary alloc] init];
    [dict setValue:params.appId forKey:@"app_id"];
    [dict setValue:@(params.instanceId) forKey:@"ai_agent_instance_id"];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"[AgentApi][REQ] url %@, body: %@", urlRequest, jsonStr);
    
    request.HTTPBody = jsonData;
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:request
                   completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSDictionary *resposneDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"[AgentApi][RESP] url %@, statusCode:%ld, response: %@", urlRequest, [httpResponse statusCode], resposneDict);
        if ([httpResponse statusCode] != 200) {
            return;
        }
        if (error) {
            NSLog(@"sendStartRequest fail, error: %@", error.description);
            return;
        }
        [self handleSendStopRequest:data block:block];

        }] resume];
}


#pragma mark - Private method

- (void)handleSendStartRequest:(NSData * _Nullable) data block:(void (^)(BaiduAgentApiStartResponse *))block {
    
    NSDictionary *resposne = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSNumber * instanceId = [resposne objectForKey:@"ai_agent_instance_id"];
    
    if (instanceId && [instanceId integerValue] == 0) {
        NSLog(@"handlesendHTTPRequest fail, instanceId is null");
        return;
    }
    BaiduAgentApiStartResponse * res = [[BaiduAgentApiStartResponse alloc] init];
    res.instanceId = [instanceId integerValue]; //记录instanceId
    
    NSDictionary *config = [resposne objectForKey:@"context"];
    res.token = [config objectForKey:@"token"];
    NSError * err;
    NSString * contextStr = [[NSString alloc] initWithData:[NSJSONSerialization  dataWithJSONObject:config options:0 error:&err] encoding:NSUTF8StringEncoding];
    res.context = contextStr;
    NSLog(@"[AgentApi] start response: %@", res.description);
    
    if (block) {
        block(res);
    }
    NSLog(@"handlesendHTTPRequest, resposne:%@, instanceId:%@", resposne, instanceId);
}

- (void)handleSendStopRequest:(NSData * _Nullable) data block:(void (^)(BaiduAgentApiStopResponse *))block {
    
    BaiduAgentApiStopResponse * res = [[BaiduAgentApiStopResponse alloc] init];
    if (block) {
        block(res);
    }
    NSLog(@"handleSendStopRequest, resposne:%@", data);
}

@end


@implementation BaiduAgentApiStartRequest

- (NSString *)description {
    return [NSString stringWithFormat:@"appId:%@, quicStart:%d, config:%@", self.appId, self.quicStart, self.config];
}

@end

@implementation BaiduAgentApiStartResponse

- (NSString *)description {
    return [NSString stringWithFormat:@"instanceId:%ld, token:%@, context:%@", self.instanceId, self.token, self.context];
}

@end

@implementation BaiduAgentApiStopRequest


@end

@implementation BaiduAgentApiStopResponse

@end
