package com.spot.service;

import com.spot.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Redis 最新价格获取服务
 * 从 ExchangeNew2:latestPrice（Hash）获取最新价格，由 spot-kline 从成交和K线数据写入
 *
 * @author jean
 * @date 2026-05-07
 */
@Slf4j
@Service
public class RedisLatestPriceService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 从 Redis 获取交易对最新价格
     * Redis 存储格式为 Hash：key=ExchangeNew2:latestPrice, field=symbol, value=price
     *
     * @param symbol 交易对符号（如：BTCUSDT）
     * @return 最新价格，获取失败返回 null
     */
    public BigDecimal getLatestPrice(String symbol) {
        if (symbol == null || symbol.trim().isEmpty()) {
            log.warn("交易对符号为空，无法获取最新价格");
            return null;
        }
        try {
            // field 为小写 symbol
            String field = symbol.toLowerCase();
            Object val = stringRedisTemplate.opsForHash().get(RedisKey.LATEST_PRICE, field);
            if (val == null) {
                log.warn("Redis中未找到价格数据 - Symbol: {}, Key: {}", symbol, RedisKey.LATEST_PRICE);
                return null;
            }
            String priceStr = val.toString().trim();
            if (priceStr.isEmpty()) {
                return null;
            }
            BigDecimal latestPrice = new BigDecimal(priceStr);
            if (latestPrice.compareTo(BigDecimal.ZERO) <= 0) {
                log.warn("解析出的价格无效 - Symbol: {}, Price: {}", symbol, latestPrice);
                return null;
            }
            log.debug("Redis获取最新价格成功 - Symbol: {}, Price: {}", symbol, latestPrice);
            return latestPrice;
        } catch (NumberFormatException e) {
            log.error("价格数据数值格式错误 - Symbol: {}", symbol, e);
            return null;
        } catch (Exception e) {
            log.error("从Redis获取最新价格时发生错误 - Symbol: {}", symbol, e);
            return null;
        }
    }

    /**
     * 批量获取多个交易对的最新价格
     *
     * @param symbols 交易对符号列表
     * @return 价格映射，key 为交易对符号，value 为最新价格
     */
    public Map<String, BigDecimal> batchGetLatestPrices(List<String> symbols) {
        Map<String, BigDecimal> priceMap = new HashMap<>();
        if (symbols == null || symbols.isEmpty()) {
            return priceMap;
        }
        log.info("批量获取Redis最新价格 - 交易对数量: {}", symbols.size());
        int successCount = 0;
        int failureCount = 0;
        for (String symbol : symbols) {
            BigDecimal price = getLatestPrice(symbol);
            if (price != null) {
                priceMap.put(symbol, price);
                successCount++;
            } else {
                failureCount++;
            }
        }
        log.info("批量获取Redis价格完成 - 成功: {} 个, 失败: {} 个, 总计: {} 个",
                successCount, failureCount, symbols.size());
        return priceMap;
    }

    /**
     * 测试 Redis 连接
     *
     * @return true 如果连接正常
     */
    public boolean testConnection() {
        try {
            String result = stringRedisTemplate.getConnectionFactory().getConnection().ping();
            log.info("Redis连接测试成功 - Result: {}", result);
            return true;
        } catch (Exception e) {
            log.error("Redis连接测试失败", e);
            return false;
        }
    }
}
