#include "tonestylemanager.h"
#include <QDebug>
#include <QStandardPaths>
#include <QApplication>

// 静态成员初始化
ToneStyleManager* ToneStyleManager::m_instance = nullptr;

ToneStyleManager::ToneStyleManager(QObject* parent)
    : QObject(parent)
{
    // 设置默认文件路径
    QString appDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config/kylin-aiassistant/template";
    m_dataFilePath = appDir + "/tone_styles.json";

    // 从文件加载数据
    loadFromFile();
}

ToneStyleManager::~ToneStyleManager()
{
    // 保存数据到文件
    saveToFile();
}

void ToneStyleManager::loadInitialTemplates()
{
    QFile file("://template/defaultTones.json");
    if (!file.exists())
    {
        return;
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    if (doc.isNull() || !doc.isObject())
    {
        qWarning() << "Invalid JSON format in defaultTemplate data file";
        return;
    }

    QJsonObject root = doc.object();
    QJsonArray toneStylesArray = root["toneStyles"].toArray();

    for (const QJsonValue& value : toneStylesArray)
    {
        if (value.isObject())
        {
            ToneStyle toneStyle;
            toneStyle.fromJson(value.toObject());
            addToneStyle(toneStyle);
        }
    }
}

ToneStyleManager* ToneStyleManager::getInstance()
{
    if (!m_instance) {
        m_instance = new ToneStyleManager();
    }
    return m_instance;
}

QString ToneStyleManager::generateUUID() const
{
    return QUuid::createUuid().toString(QUuid::WithoutBraces);
}

bool ToneStyleManager::addToneStyle(const ToneStyle& toneStyle)
{
    // 检查UUID是否已存在
    QString uuid = toneStyle.uuid.isEmpty() ? generateUUID() : toneStyle.uuid;
    if (toneStyleExists(uuid)) {
        qWarning() << "Tone style with UUID" << uuid << "already exists";
        return false;
    }

    ToneStyle newToneStyle = toneStyle;
    newToneStyle.uuid = uuid;

    m_toneStyles.append(newToneStyle);

    // 保存到文件
    if (saveToFile()) {
        emit toneStyleAdded(newToneStyle);
        return true;
    } else {
        // 如果保存失败，回滚
        m_toneStyles.removeOne(newToneStyle);
        return false;
    }
}

bool ToneStyleManager::removeToneStyle(const QString& uuid)
{
    for (int i = 0; i < m_toneStyles.size(); ++i) {
        if (m_toneStyles[i].uuid == uuid) {
            ToneStyle removedToneStyle = m_toneStyles[i];
            m_toneStyles.removeAt(i);

            // 保存到文件
            if (saveToFile()) {
                emit toneStyleRemoved(uuid);
                return true;
            } else {
                // 如果保存失败，回滚
                m_toneStyles.insert(i, removedToneStyle);
                return false;
            }
        }
    }

    qWarning() << "Tone style with UUID" << uuid << "not found";
    return false;
}

bool ToneStyleManager::updateToneStyle(const QString& uuid, const ToneStyle& newData)
{
    for (int i = 0; i < m_toneStyles.size(); ++i) {
        if (m_toneStyles[i].uuid == uuid) {
            ToneStyle oldToneStyle = m_toneStyles[i];
            ToneStyle updatedToneStyle = newData;
            updatedToneStyle.uuid = uuid; // 确保UUID不变

            m_toneStyles[i] = updatedToneStyle;

            // 保存到文件
            if (saveToFile()) {
                emit toneStyleUpdated(updatedToneStyle);
                return true;
            } else {
                // 如果保存失败，回滚
                m_toneStyles[i] = oldToneStyle;
                return false;
            }
        }
    }

    qWarning() << "Tone style with UUID" << uuid << "not found for update";
    return false;
}

ToneStyle ToneStyleManager::getToneStyle(const QString& uuid) const
{
    for (const ToneStyle& toneStyle : m_toneStyles) {
        if (toneStyle.uuid == uuid) {
            return toneStyle;
        }
    }

    return ToneStyle(); // 返回空结构体
}

QList<ToneStyle> ToneStyleManager::getAllToneStyles() const
{
    return m_toneStyles;
}

QList<ToneStyle> ToneStyleManager::findToneStylesByName(const QString& name) const
{
    QList<ToneStyle> result;

    for (const ToneStyle& toneStyle : m_toneStyles) {
        if (toneStyle.toneName.contains(name, Qt::CaseInsensitive)) {
            result.append(toneStyle);
        }
    }

    return result;
}

bool ToneStyleManager::toneStyleExists(const QString& uuid) const
{
    for (const ToneStyle& toneStyle : m_toneStyles) {
        if (toneStyle.uuid == uuid) {
            return true;
        }
    }
    return false;
}

bool ToneStyleManager::loadFromFile(const QString& filePath)
{
    QString loadPath = filePath.isEmpty() ? m_dataFilePath : filePath;

    QFile file(loadPath);
    if (!file.exists()) {
        qInfo() << "Tone style data file does not exist, will create new one:" << loadPath;
        loadInitialTemplates();
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open tone style data file for reading:" << loadPath;
        return false;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    if (doc.isNull() || !doc.isObject()) {
        qWarning() << "Invalid JSON format in tone style data file:" << loadPath;
        return false;
    }

    QJsonObject root = doc.object();
    QJsonArray toneStylesArray = root["toneStyles"].toArray();

    m_toneStyles.clear();
    for (const QJsonValue& value : toneStylesArray) {
        if (value.isObject()) {
            ToneStyle toneStyle;
            toneStyle.fromJson(value.toObject());
            m_toneStyles.append(toneStyle);
        }
    }

    m_dataFilePath = loadPath;
    emit dataLoaded();

    qInfo() << "Loaded" << m_toneStyles.size() << "tone styles from" << loadPath;
    return true;
}

bool ToneStyleManager::saveToFile(const QString& filePath)
{
    QString savePath = filePath.isEmpty() ? m_dataFilePath : filePath;

    QJsonArray toneStylesArray;
    for (const ToneStyle& toneStyle : m_toneStyles) {
        toneStylesArray.append(toneStyle.toJson());
    }

    QJsonObject root;
    root["toneStyles"] = toneStylesArray;

    QJsonDocument doc(root);
    QByteArray jsonData = doc.toJson(QJsonDocument::Indented);

    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Failed to open tone style data file for writing:" << savePath;
        return false;
    }

    file.write(jsonData);
    file.close();

    if (!filePath.isEmpty()) {
        m_dataFilePath = savePath;
    }

    emit dataSaved();
    qInfo() << "Saved" << m_toneStyles.size() << "tone styles to" << savePath;
    return true;
}
