#include "eaichatinfojsoncontrol.h"
#include <QStandardPaths>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QTextStream>
#include <QMap>

EaiChatInfoJsonControl::EaiChatInfoJsonControl()
{
    auto dirPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    m_chatInfoPath = dirPath + "/ChatInfo.json";
    m_conversationInfoPath = dirPath + "/ConversationHistory.json";
}

EaiChatInfoJsonControl &EaiChatInfoJsonControl::localChatInfoJsonControl()
{
    static EaiChatInfoJsonControl control;
    return control;
}

void EaiChatInfoJsonControl::updateConvsInfo(const QString &assistantId, const QString &conversationId, const QString &assistantDisplayName, QVector<uos_ai::Conversations> conversations)
{
    // 1. 获取缓存目录路径
    QString dirPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    // 2. 更新对话文件 --------------------------------------------
    QString conversationFilePath = dirPath + "/" + assistantId + "_" + conversationId + ".json";

    QJsonObject rootObj;
    rootObj["assistantId"] = assistantId;
    rootObj["conversationId"] = conversationId;

    QJsonArray convsArray;
    QByteArray convsData;
    uos_ai::Conversations::convs2Json(convsData, conversations);
    convsArray = QJsonDocument::fromJson(convsData).array();

    rootObj["conversations"] = convsArray;

    QJsonDocument jsonDoc(rootObj);

    QFile conversationfile(conversationFilePath);
    if (conversationfile.open(QIODevice::WriteOnly)) {
        conversationfile.write(jsonDoc.toJson());
        conversationfile.close();
        qDebug() << "对话文件创建成功:" << conversationFilePath;
    } else {
        qWarning() << "无法创建对话文件:" << conversationFilePath;
    }

    // 3. 更新ConversationHistory.json -----------

    QFile historyFile(m_conversationInfoPath);
    if (!historyFile.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开历史文件:" << m_conversationInfoPath;
        return;
    }

    QByteArray historyData = historyFile.readAll();
    historyFile.close();

    QJsonDocument historyDoc = QJsonDocument::fromJson(historyData);
    if (historyDoc.isNull()) {
        qWarning() << "无效的历史文件格式";
        return;
    }

    QJsonObject historyObj = historyDoc.object();

    QString historyKey = assistantId + "_" + conversationId;

    if (historyObj.contains(historyKey)) {
        QJsonObject entry = historyObj[historyKey].toObject();
        entry["conversationTitle"] = conversations.first().question.displayContent;
        entry["conversationTimestamp"] = QDateTime::currentSecsSinceEpoch(); // 更新为当前时间戳
        entry["assistantDisplayName"] = assistantDisplayName;
        // 替换原来的条目
        historyObj[historyKey] = entry;
        qDebug() << "更新时间戳:" << historyKey;
    } else {
        qWarning() << "未找到对话记录:" << historyKey;
        return;
    }

    // 新增历史记录数量控制
    QVector<QPair<QString, qint64>> validEntries;
    for (auto it = historyObj.constBegin(); it != historyObj.constEnd(); ++it) {
        QJsonObject entry = it.value().toObject();
        if (!entry["conversationTitle"].toString().isEmpty()) {
            validEntries.append(qMakePair(it.key(), entry["conversationTimestamp"].toVariant().toLongLong()));
        }
    }

    // 当有效条目超过100时清理旧记录
    if (validEntries.size() > 100) {
        // 按时间戳升序排序
        std::sort(validEntries.begin(), validEntries.end(), 
            [](const QPair<QString, qint64> &a, const QPair<QString, qint64> &b) {
                return a.second < b.second;
            });

        // 计算需要删除的数量
        int removeCount = validEntries.size() - 100;
        for (int i = 0; i < removeCount; ++i) {
            historyObj.remove(validEntries[i].first);
            qDebug() << "移除旧记录:" << validEntries[i].first;
        }
    }

    // 写回修改后的数据
    if (historyFile.open(QIODevice::WriteOnly)) {
        historyFile.write(QJsonDocument(historyObj).toJson());
        historyFile.close();
        qDebug() << "历史文件更新成功";
    } else {
        qWarning() << "无法写入历史文件";
    }
}

void EaiChatInfoJsonControl::getAllConvsInfo(QMap<QString, QJsonDocument> &assisConvs)
{
    QJsonArray convsArray;

    QFile file(m_conversationInfoPath);
    if (!file.open(QIODevice::ReadOnly)) {
        // 打开文件失败
        QJsonDocument jsonDocError(convsArray);
        return;
    }
    // 读取文件内容
    QByteArray jsonData = file.readAll();
    file.close();
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument chatInfoDoc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "JSON解析错误:" << parseError.errorString();
        return;
    }

    if (!chatInfoDoc.isObject()) {
        qWarning() << "根元素不是对象";
        return;
    }

    QJsonObject jsonObject = chatInfoDoc.object();
    for (auto it = jsonObject.constBegin(); it != jsonObject.constEnd(); ++it) {
        if (it.value().isObject()) {
            // 创建包含单个对象的文档
            QJsonObject convObj = it.value().toObject();
            QJsonDocument jsonDoc(convObj);
            assisConvs[it.key()] = jsonDoc;
        } else {
            qWarning() << "值不是对象:" << it.key();
        }
    }
}

bool EaiChatInfoJsonControl::getConvsInfo(const QString &assistantId, const QString &conversationId , QVector<uos_ai::Conversations> &conversations)
{
    QJsonArray convsArray;

    // Get the directory path
    auto dirPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    // Create the full file path (assuming the file is named "conversations.json")
    QString conversationFilePath = dirPath + "/" + assistantId + "_" + conversationId+".json";
    QFile file(conversationFilePath);
    if (!file.open(QIODevice::ReadOnly)) {
        // 打开文件失败
        QJsonDocument jsonDocError(convsArray);
        return false;
    }
    // 读取文件内容
    QByteArray jsonData = file.readAll();
    file.close();
    QJsonDocument chatInfoDoc = QJsonDocument::fromJson(jsonData);
    QJsonObject jsonObject = chatInfoDoc.object();
    QJsonDocument jsonDoc(jsonObject.find("conversations").value().toArray());
    uos_ai::Conversations::json2Convs(conversations, jsonDoc.toJson());

    // 时间戳更新
    QFile historyFile(m_conversationInfoPath);
    if (!historyFile.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开历史文件:" << m_conversationInfoPath;
        return false;
    }

    QByteArray historyData = historyFile.readAll();
    historyFile.close();

    QJsonDocument historyDoc = QJsonDocument::fromJson(historyData);
    if (historyDoc.isNull()) {
        qWarning() << "无效的历史文件格式";
        return false;
    }

    QJsonObject historyObj = historyDoc.object();

    QString historyKey = assistantId + "_" + conversationId;

    if (historyObj.contains(historyKey)) {
        QJsonObject entry = historyObj[historyKey].toObject();
        entry["accessTimestamp"] = QDateTime::currentSecsSinceEpoch(); // 更新为当前时间戳
        // 替换原来的条目
        historyObj[historyKey] = entry;
        qDebug() << "更新时间戳:" << historyKey;
    } else {
        qWarning() << "未找到对话记录:" << historyKey;
    }

    if (historyFile.open(QIODevice::WriteOnly)) {
        historyFile.write(QJsonDocument(historyObj).toJson());
        historyFile.close();
        qDebug() << "历史文件更新成功";
    } else {
        qWarning() << "无法写入历史文件";
    }
    return true;
}

QString EaiChatInfoJsonControl::createConvs(const QString &assistantId)
{
    //清理旧的空对话
    QMap<QString, QJsonDocument> existingConvs;
    getAllConvsInfo(existingConvs);

    for (auto it = existingConvs.constBegin(); it != existingConvs.constEnd(); ++it) {
        QJsonObject conv = it.value().object();
        if (conv["assistantId"] == assistantId && conv["conversationTitle"].toString().isEmpty())
            removeConvs(assistantId, conv["conversationId"].toString());
    }

    // Current timestamp
    qint64 timestamp = QDateTime::currentSecsSinceEpoch();
    QString conversationId = QString::number(timestamp);

    // Create the new conversation entry
    QJsonObject newConversation;
    newConversation["assistantId"] = assistantId;
    newConversation["conversationId"] = conversationId;
    newConversation["conversationTitle"] = "";
    newConversation["conversationTimestamp"] = 0;
    newConversation["assistantDisplayName"] = "";
    newConversation["accessTimestamp"] = timestamp;

    // Key for the JSON object (assistantId_conversationId)
    QString key = assistantId + "_" + conversationId;

    // Read existing data
    QJsonObject rootObject;
    QFile conversationInfofile(m_conversationInfoPath);

    if (conversationInfofile.exists() && conversationInfofile.open(QIODevice::ReadOnly)) {
        QByteArray data = conversationInfofile.readAll();
        conversationInfofile.close();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (doc.isObject()) {
            rootObject = doc.object();
        }
    }
    rootObject[key] = newConversation;

    // Write back to file
    if (conversationInfofile.open(QIODevice::WriteOnly)) {
        QJsonDocument doc(rootObject);
        conversationInfofile.write(doc.toJson());
        conversationInfofile.close();
    } else {
        qWarning() << "Could not open conversation file for writing:" << m_conversationInfoPath;
    }
    return conversationId;
}

void EaiChatInfoJsonControl::removeConvs(const QString &assistantId, const QString &conversationId)
{
    QString dirPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    // 1. 读取现有的 ConversationHistory.json
    QFile historyFile(m_conversationInfoPath);
    if (!historyFile.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开历史文件:" << m_conversationInfoPath;
        return;
    }

    QByteArray historyData = historyFile.readAll();
    historyFile.close();

    QJsonDocument historyDoc = QJsonDocument::fromJson(historyData);
    if (historyDoc.isNull()) {
        qWarning() << "无效的历史文件格式";
        return;
    }

    QJsonObject historyObj = historyDoc.object();

    // 2. 构建要删除的键 (assistantId + "_" + conversationId)
    QString keyToDelete = assistantId + "_" + conversationId;

    // 3. 删除对应的项
    if (historyObj.contains(keyToDelete)) {
        historyObj.remove(keyToDelete);
        qDebug() << "从历史记录中删除:" << keyToDelete;
    } else {
        qWarning() << "未找到要删除的历史记录项:" << keyToDelete;
    }

    // 4. 写回文件
    if (historyFile.open(QIODevice::WriteOnly)) {
        historyFile.write(QJsonDocument(historyObj).toJson());
        historyFile.close();
    } else {
        qWarning() << "无法写入历史文件";
    }

    // 5. 删除对话文件
    QString conversationFilePath = dirPath + "/" + keyToDelete + ".json";
    QFile conversationFile(conversationFilePath);

    if (conversationFile.exists()) {
        if (conversationFile.remove()) {
            qDebug() << "成功删除对话文件:" << conversationFilePath;
        } else {
            qWarning() << "无法删除对话文件:" << conversationFile.errorString();
        }
    } else {
        qWarning() << "对话文件不存在:" << conversationFilePath;
    }
}

bool EaiChatInfoJsonControl::isConvsExist(const QString &assistantId, const QString &conversationId)
{
    QJsonArray convsArray;

    QFile file(m_conversationInfoPath);
    if (!file.open(QIODevice::ReadOnly)) {
        // 打开文件失败
        QJsonDocument jsonDocError(convsArray);
        return false;
    }
    // 读取文件内容
    QByteArray jsonData = file.readAll();
    file.close();
    // 解析JSON
    QJsonDocument chatInfoDoc = QJsonDocument::fromJson(jsonData);
    QJsonObject jsonObject = chatInfoDoc.object();
    QString conversationFileName = assistantId+"_"+conversationId;
    return jsonObject.find(conversationFileName) != jsonObject.constEnd();
}

QString EaiChatInfoJsonControl::findLatestConversation(const QString& targetAssistantId) {
    QMap<QString, QJsonDocument> allConvs;
    getAllConvsInfo(allConvs);  // 获取全部会话信息

    QJsonDocument latestConversation;
    qint64 maxTimestamp = 0;

    QMapIterator<QString, QJsonDocument> it(allConvs);
    while (it.hasNext()) {
        it.next();
        QJsonObject convObj = it.value().object();
        if (convObj["assistantId"].toString() != targetAssistantId) continue;
        qint64 timestamp = convObj["accessTimestamp"].toVariant().toLongLong();
        if (timestamp > maxTimestamp) {
            maxTimestamp = timestamp;
            latestConversation = it.value();
        }
    }

    if (latestConversation.isEmpty()) {
        createConvs(targetAssistantId);
        return findLatestConversation(targetAssistantId);
    }

    return latestConversation.toJson(QJsonDocument::Indented);
}
