using System.Text.Json;
using System.Text.Json.Serialization;

namespace AudioWallpaper.ActivityWatch {

    // 定义数据模型
    public class ApiResponse {
        [JsonPropertyName("code")]
        public int Code { get; set; }

        [JsonPropertyName("data")]
        public DataItem[] Data { get; set; }
    }

    public class DataItem {
        [JsonPropertyName("message")]
        public MessageContent Message { get; set; }
    }

    public class MessageContent {
        [JsonPropertyName("content")]
        public string Content { get; set; }
    }

    public class FocusStatusRecord {
        [JsonPropertyName("time_slice")]
        public string TimeSlice { get; set; }

        [JsonPropertyName("focus_state")]
        public string FocusState { get; set; }

        [JsonPropertyName("productivity_score")]
        public double ProductivityScore { get; set; }

        [JsonPropertyName("message")]
        public string Message { get; set; }
    }

    public class FocusStatusParser {
        public FocusStatusRecord GetLatestRecord(string jsonResponse) {
            // 解析外层响应
            var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse);

            if (apiResponse?.Data == null || apiResponse.Data.Length == 0)
                throw new InvalidOperationException("无效的API响应数据");

            // 提取内容字符串（包含Markdown代码块）
            string content = apiResponse.Data[0].Message.Content;

            // 去除Markdown代码块标记
            string cleanJson = content
                .Replace("```json", "")
                .Replace("```", "")
                .Trim();

            // 解析内部JSON数组
            var records = JsonSerializer.Deserialize<FocusStatusRecord[]>(cleanJson);

            if (records == null || records.Length == 0)
                throw new InvalidOperationException("未找到专注状态记录");

            // 返回最新的记录（数组的第一个元素）
            return records[0];
        }
    }
}
