#include "rulesengine.h"
#include "../db/dao/ruledao.h"
#include "../db/dao/categorydao.h"
#include "../db/dao/mailitemdao.h"
#include "../db/dao/folderdao.h"
#include "mailservice.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>

RulesEngine::ProgressCallback RulesEngine::s_progressCallback = nullptr;

void RulesEngine::setProgressCallback(ProgressCallback cb)
{
    s_progressCallback = cb;
}

QVector<RulesEngine::ActionResult> RulesEngine::evaluateAndExecute(const EvaluationContext& ctx)
{
    QVector<ActionResult> results;
    if (!ctx.mailItem) return results;

    QVector<Rule> rules = RuleDao::findAllEnabled();
    // Filter rules applicable to this account
    QVector<Rule> applicableRules;
    for (const Rule& rule : rules) {
        if (rule.isGlobal() || rule.accountId == ctx.accountId) {
            applicableRules.append(rule);
        }
    }

    bool stopProcessing = false;
    for (const Rule& rule : applicableRules) {
        if (stopProcessing) break;

        if (s_progressCallback) {
            s_progressCallback(0, 0, rule.name);
        }

        if (matchesConditions(rule, ctx)) {
            qDebug() << "[RulesEngine] Rule matched:" << rule.name << "for mail" << ctx.mailItem->id();
            
            for (const RuleAction& action : rule.actions) {
                ActionResult result = executeAction(action, ctx);
                results.append(result);
                
                if (shouldStopProcessing(action)) {
                    stopProcessing = true;
                    break;
                }
            }
        }
    }
    return results;
}

bool RulesEngine::matchesConditions(const Rule& rule, const EvaluationContext& ctx)
{
    if (rule.conditions.isEmpty()) return true;

    if (rule.matchAll) {
        // AND logic: all conditions must match
        for (const RuleCondition& cond : rule.conditions) {
            if (!matchCondition(cond, ctx)) return false;
        }
        return true;
    } else {
        // OR logic: at least one condition must match
        for (const RuleCondition& cond : rule.conditions) {
            if (matchCondition(cond, ctx)) return true;
        }
        return false;
    }
}

bool RulesEngine::matchCondition(const RuleCondition& cond, const EvaluationContext& ctx)
{
    QString fieldValue = getFieldValue(cond, ctx);
    return cond.match(fieldValue);
}

QString RulesEngine::getFieldValue(const RuleCondition& cond, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return QString();

    switch (cond.field) {
        case RuleCondition::From:
            return ctx.mailItem->sender();
        case RuleCondition::To:
            return ctx.mailItem->to();
        case RuleCondition::Cc:
            return ctx.mailItem->cc();
        case RuleCondition::Subject:
            return ctx.mailItem->subject();
        case RuleCondition::Body:
            return ctx.mailItem->bodyHtml(); // or plain text version
        case RuleCondition::HasAttachment:
            return ctx.mailItem->attachments().isEmpty() ? "false" : "true";
        case RuleCondition::Size:
            return QString::number(ctx.mailItem->size());
        case RuleCondition::Date:
            return ctx.mailItem->date().toString(Qt::ISODate);
        case RuleCondition::Flagged:
            return ctx.mailItem->isFlagged() ? "true" : "false";
        case RuleCondition::Read:
            return ctx.mailItem->isRead() ? "true" : "false";
        default:
            return QString();
    }
}

RulesEngine::ActionResult RulesEngine::executeAction(const RuleAction& action, const EvaluationContext& ctx)
{
    switch (action.type) {
        case RuleAction::MoveToFolder:
            return executeMoveToFolder(action, ctx);
        case RuleAction::MarkAsRead:
            return executeMarkAsRead(action, ctx);
        case RuleAction::MarkAsFlagged:
            return executeMarkAsFlagged(action, ctx);
        case RuleAction::Delete:
            return executeDelete(action, ctx);
        case RuleAction::AssignCategory:
            return executeAssignCategory(action, ctx);
        case RuleAction::RemoveCategory:
            return executeRemoveCategory(action, ctx);
        case RuleAction::ForwardTo:
            return executeForwardTo(action, ctx);
        case RuleAction::SetPriority:
            return executeSetPriority(action, ctx);
        default:
            return {false, QString("Unknown action type: %1").arg(static_cast<int>(action.type))};
    }
}

RulesEngine::ActionResult RulesEngine::executeMoveToFolder(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool ok;
    qint64 targetFolderId = action.value.toLongLong(&ok);
    if (!ok) return {false, "Invalid folder ID"};
    
    // Use MailService to move the mail
    // For now, just update the folderId in MailCopy
    QSqlDatabase db = DatabaseManager::instance().database();
    QSqlQuery query(db);
    query.prepare("UPDATE MailCopy SET folderId = :folderId WHERE id = :id");
    query.bindValue(":folderId", targetFolderId);
    query.bindValue(":id", ctx.mailItem->id());
    
    if (!query.exec()) {
        return {false, query.lastError().text()};
    }
    
    return {true, QString("Moved to folder %1").arg(targetFolderId)};
}

RulesEngine::ActionResult RulesEngine::executeMarkAsRead(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool read = action.value.toLower() != "false";
    
    QSqlDatabase db = DatabaseManager::instance().database();
    QSqlQuery query(db);
    query.prepare("UPDATE MailCopy SET read = :read WHERE id = :id");
    query.bindValue(":read", read ? 1 : 0);
    query.bindValue(":id", ctx.mailItem->id());
    
    if (!query.exec()) {
        return {false, query.lastError().text()};
    }
    
    return {true, QString("Marked as %1").arg(read ? "read" : "unread")};
}

RulesEngine::ActionResult RulesEngine::executeMarkAsFlagged(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool flagged = action.value.toLower() != "false";
    
    QSqlDatabase db = DatabaseManager::instance().database();
    QSqlQuery query(db);
    query.prepare("UPDATE MailCopy SET flagged = :flagged WHERE id = :id");
    query.bindValue(":flagged", flagged ? 1 : 0);
    query.bindValue(":id", ctx.mailItem->id());
    
    if (!query.exec()) {
        return {false, query.lastError().text()};
    }
    
    return {true, QString("Marked as %1").arg(flagged ? "flagged" : "unflagged")};
}

RulesEngine::ActionResult RulesEngine::executeDelete(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool success = MailItemDao::remove(ctx.mailItem->id());
    return {success, success ? "Deleted" : "Delete failed"};
}

RulesEngine::ActionResult RulesEngine::executeAssignCategory(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool ok;
    qint64 categoryId = action.value.toLongLong(&ok);
    if (!ok) return {false, "Invalid category ID"};
    
    bool success = CategoryDao::assignToMail(ctx.mailItem->id(), categoryId);
    return {success, success ? "Category assigned" : "Assign failed"};
}

RulesEngine::ActionResult RulesEngine::executeRemoveCategory(const RuleAction& action, const EvaluationContext& ctx)
{
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool ok;
    qint64 categoryId = action.value.toLongLong(&ok);
    if (!ok) return {false, "Invalid category ID"};
    
    bool success = CategoryDao::removeFromMail(ctx.mailItem->id(), categoryId);
    return {success, success ? "Category removed" : "Remove failed"};
}

RulesEngine::ActionResult RulesEngine::executeForwardTo(const RuleAction& action, const EvaluationContext& ctx)
{
    // This would require MailService integration - placeholder for now
    if (!ctx.mailItem) return {false, "No mail item"};
    
    QString toAddr = action.value;
    if (toAddr.isEmpty() || !toAddr.contains("@")) {
        return {false, "Invalid forward address"};
    }
    
    // TODO: Integrate with MailService::sendMail
    qDebug() << "[RulesEngine] Forward to:" << toAddr << "for mail" << ctx.mailItem->id();
    return {true, QString("Forwarded to %1 (placeholder)").arg(toAddr)};
}

RulesEngine::ActionResult RulesEngine::executeSetPriority(const RuleAction& action, const EvaluationContext& ctx)
{
    // Priority could be stored as a custom field or flagged status
    // For now, use flagged for high priority
    if (!ctx.mailItem) return {false, "No mail item"};
    
    bool high = action.value.toLower() == "high";
    
    QSqlDatabase db = DatabaseManager::instance().database();
    QSqlQuery query(db);
    query.prepare("UPDATE MailCopy SET flagged = :flagged WHERE id = :id");
    query.bindValue(":flagged", high ? 1 : 0);
    query.bindValue(":id", ctx.mailItem->id());
    
    if (!query.exec()) {
        return {false, query.lastError().text()};
    }
    
    return {true, QString("Priority set to %1").arg(high ? "high" : "normal")};
}

bool RulesEngine::shouldStopProcessing(const RuleAction& action)
{
    return action.type == RuleAction::StopProcessing;
}

int RulesEngine::runRulesOnFolder(qint64 folderId, qint64 accountId)
{
    QVector<MailItem> mails = MailItemDao::findByFolderId(folderId);
    int processed = 0;
    
    for (int i = 0; i < mails.size(); ++i) {
        if (s_progressCallback) {
            s_progressCallback(i, mails.size(), QString("Procesando %1/%2").arg(i+1).arg(mails.size()));
        }
        
        EvaluationContext ctx;
        ctx.mailItem = &mails[i];
        ctx.folderId = folderId;
        ctx.accountId = accountId;
        
        evaluateAndExecute(ctx);
        processed++;
    }
    
    return processed;
}

int RulesEngine::runRulesOnMails(const QVector<qint64>& mailIds, qint64 accountId)
{
    int processed = 0;
    
    for (int i = 0; i < mailIds.size(); ++i) {
        if (s_progressCallback) {
            s_progressCallback(i, mailIds.size(), QString("Procesando %1/%2").arg(i+1).arg(mailIds.size()));
        }
        
        auto mailOpt = MailItemDao::findById(mailIds[i]);
        if (!mailOpt.has_value()) continue;
        
        EvaluationContext ctx;
        ctx.mailItem = &mailOpt.value();
        ctx.accountId = accountId;
        
        evaluateAndExecute(ctx);
        processed++;
    }
    
    return processed;
}