using Newtonsoft.Json;
using System.Text;

namespace TechHelper.Client.AI
{
	public class Message
	{
		[JsonProperty("role")]
		public string Role { get; set; }

		[JsonProperty("content")]
		public string Content { get; set; }
	}

	// 系统消息
	public class SystemMessage : Message
	{
		public SystemMessage(string content)
		{
			Role = "system";
			Content = content;
		}
	}

	// 用户消息
	public class UserMessage : Message
	{
		public UserMessage(string content)
		{
			Role = "user";
			Content = content;
		}
	}

	// 助手消息
	public class AssistantMessage : Message
	{
		public AssistantMessage(string content)
		{
			Role = "assistant";
			Content = content;
		}
	}

	// GLM-Z1 Chat Completions API 请求体
	public class ChatCompletionRequest
	{
		[JsonProperty("model")]
		public string Model { get; set; }

		[JsonProperty("messages")]
		public List<Message> Messages { get; set; }

		[JsonProperty("request_id")]
		public string RequestId { get; set; }

		[JsonProperty("do_sample")]
		public bool? DoSample { get; set; }

		[JsonProperty("stream")]
		public bool? Stream { get; set; }

		[JsonProperty("temperature")]
		public float? Temperature { get; set; }

		[JsonProperty("top_p")]
		public float? TopP { get; set; }

		[JsonProperty("max_tokens")]
		public int? MaxTokens { get; set; }

		[JsonProperty("stop")]
		public List<string> Stop { get; set; }

		[JsonProperty("user_id")]
		public string UserId { get; set; }
	}

	// GLM-Z1 Chat Completions API 响应体
	public class ChatCompletionResponse
	{
		[JsonProperty("id")]
		public string Id { get; set; }

		[JsonProperty("created")]
		public long Created { get; set; }

		[JsonProperty("model")]
		public string Model { get; set; }

		[JsonProperty("choices")]
		public List<CompletionChoice> Choices { get; set; }

		[JsonProperty("usage")]
		public CompletionUsage Usage { get; set; }
	}

	public class CompletionChoice
	{
		[JsonProperty("index")]
		public int Index { get; set; }

		[JsonProperty("finish_reason")]
		public string FinishReason { get; set; }

		[JsonProperty("message")]
		public CompletionMessage Message { get; set; }

		// 流式响应中的delta
		[JsonProperty("delta")]
		public CompletionMessage Delta { get; set; }
	}

	public class CompletionMessage
	{
		[JsonProperty("role")]
		public string Role { get; set; }

		[JsonProperty("content")]
		public string Content { get; set; }
	}

	public class CompletionUsage
	{
		[JsonProperty("prompt_tokens")]
		public int PromptTokens { get; set; }

		[JsonProperty("completion_tokens")]
		public int CompletionTokens { get; set; }

		[JsonProperty("total_tokens")]
		public int TotalTokens { get; set; }
	}

	// 异步调用响应
	public class AsyncTaskStatus
	{
		[JsonProperty("request_id")]
		public string RequestId { get; set; }

		[JsonProperty("id")]
		public string Id { get; set; }

		[JsonProperty("model")]
		public string Model { get; set; }

		[JsonProperty("task_status")]
		public string TaskStatus { get; set; }
	}

	// 异步查询结果响应
	public class AsyncCompletion : AsyncTaskStatus
	{
		[JsonProperty("choices")]
		public List<CompletionChoice> Choices { get; set; }

		[JsonProperty("usage")]
		public CompletionUsage Usage { get; set; }
	}

	// GLM-Z1 API 客户端
	public class GLMZ1Client
	{
		private readonly HttpClient _httpClient;
		private readonly string _apiKey;
		private const string BaseUrl = "https://open.bigmodel.cn/api/paas/v4/";

		public GLMZ1Client(string apiKey)
		{
			_apiKey = apiKey;
			_httpClient = new HttpClient();
			_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
			_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
		}

		// 同步调用 Chat Completions API
		public async Task<ChatCompletionResponse> ChatCompletionsSync(ChatCompletionRequest request)
		{
			request.Stream = false; // 确保同步调用时 stream 为 false
			var jsonContent = JsonConvert.SerializeObject(request);
			var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

			var response = await _httpClient.PostAsync($"{BaseUrl}chat/completions", httpContent);
			response.EnsureSuccessStatusCode(); // 确保请求成功

			var responseString = await response.Content.ReadAsStringAsync();
			return JsonConvert.DeserializeObject<ChatCompletionResponse>(responseString);
		}

		// 异步调用 Chat Completions API
		public async Task<AsyncTaskStatus> ChatCompletionsAsync(ChatCompletionRequest request)
		{
			var jsonContent = JsonConvert.SerializeObject(request);
			var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

			var response = await _httpClient.PostAsync($"{BaseUrl}async/chat/completions", httpContent);
			response.EnsureSuccessStatusCode();

			var responseString = await response.Content.ReadAsStringAsync();
			return JsonConvert.DeserializeObject<AsyncTaskStatus>(responseString);
		}

		// 查询异步任务结果
		public async Task<AsyncCompletion> RetrieveCompletionResult(string taskId)
		{
			var response = await _httpClient.GetAsync($"{BaseUrl}async-result/{taskId}");
			response.EnsureSuccessStatusCode();

			var responseString = await response.Content.ReadAsStringAsync();
			return JsonConvert.DeserializeObject<AsyncCompletion>(responseString);
		}

		// TODO: 实现流式调用，这会涉及循环读取 HttpResponseMessage.Content.ReadAsStreamAsync()
		// 并解析 SSE 事件，此处为简化暂不提供完整实现。
		// public async IAsyncEnumerable<ChatCompletionResponse> ChatCompletionsStream(ChatCompletionRequest request) { ... }
	}
}
