// Mind 模型文件往返测试:load -> decide -> learn -> save -> reload
#include "mind_strategy.hpp"
#include "text_feature.hpp"
#include <cstdio>
#include <string>
#include <cstdlib>

using namespace quant;

static int checks = 0, fails = 0;
static void check(const char* name, bool ok, const char* detail = "") {
    ++checks;
    if (!ok) ++fails;
    std::printf("[%s] %s %s\n", ok ? "PASS" : "FAIL", name, detail);
}

int main() {
    std::string path = "/tmp/test_mind_model.json";

    // 1) 冷启动:无模型文件 → load 返回 false(正常)
    MindStrategy s1;
    check("cold start load missing", !s1.load_model("/tmp/nonexistent.json"));

    // 2) 决策:喂几根 bar,必须有动作输出
    Bar bar{};
    bar.volume = 1500.0;
    Indicators ind{};
    ind.rsi = 65.2;
    ind.trend_score = 0.8;
    ind.atr = 2.3;
    Position pos{};
    pos.unrealized_pnl = 120.5;

    std::string a = s1.on_bar(bar, ind, pos);
    bool action_valid = (a == "buy" || a == "sell" || a == "hold");
    check("decide returns valid action", action_valid, a.c_str());

    // 3) 学习:反馈后记忆 +1
    size_t mem_before = s1.mind().memories().size();
    s1.on_filled(120.5);
    size_t mem_after = s1.mind().memories().size();
    check("learn grows memory", mem_after == mem_before + 1);

    // 4) 保存
    s1.save_model(path);
    check("save model", std::ifstream(path).is_open());

    // 5) 重新加载:新实例读同一文件,记忆应恢复
    MindStrategy s2;
    check("reload model", s2.load_model(path));
    check("reload restores memory", s2.mind().memories().size() == mem_after);

    // 6) 演进:记忆足够后 evolve 不崩
    s1.evolve();
    check("evolve ok", true);

    // 7) 决策一致性:同状态两次决策都有效
    std::string a2 = s1.on_bar(bar, ind, pos);
    check("second decide valid", a2 == "buy" || a2 == "sell" || a2 == "hold", a2.c_str());

    // 8) 文本信号喂进状态向量:带利空新闻 → 状态 [5..8] 被填充
    MindStrategy s3;
    s3.on_bar(bar, ind, pos, "Bitcoin crashes! Regulators crackdown on exchange! Sell!");
    // 利空文本: sentiment < 0, bearish_ratio > 0
    // 通过 Mind 的记忆验证状态向量是否含文本特征
    // (on_bar 会 learn 前先 decide;此处用一次完整决策 + 反馈)
    // 直接验证:带文本决策动作有效
    std::string a3 = s3.on_bar(bar, ind, pos, "暴跌 恐慌 监管打压 黑客攻击");
    check("text-driven decide valid", a3 == "buy" || a3 == "sell" || a3 == "hold", a3.c_str());

    // 9) 文本特征维度: 利空新闻的 sentiment 应为负
    TextFeature tf;
    auto feat = tf.extract("Bitcoin crashes! Regulators crackdown! Sell!");
    check("text sentiment negative", feat.sentiment < 0.0);
    check("text bearish ratio > 0", feat.bearish_ratio > 0.0);

    // 清理
    std::remove(path.c_str());

    std::printf("\n==== %d checks, %d fails ====\n", checks, fails);
    return fails ? 1 : 0;
}