#!/usr/bin/env python3
"""
RIVER/USDT K线监控脚本 - 纯脚本版
修复版：正确的过滤逻辑
"""

import json
import subprocess
import os
from datetime import datetime

SYMBOLS = ["riverusdt"]
PERIODS = ["1min", "5min", "15min"]
NOTIFY_FILE = "/root/.openclaw/workspace/memory/kline-notify.json"
LOG_FILE = "/root/.openclaw/workspace/memory/kline-log.md"
TG_GROUP = "-1003737456065"

def curl_cmd(url):
    result = subprocess.run(["curl", "-s", url], capture_output=True, text=True)
    return result.stdout

def get_klines(symbol, period, size=20):
    url = f"https://api.huobi.pro/market/history/kline?symbol={symbol}&period={period}&size={size}"
    data = curl_cmd(url)
    try:
        return json.loads(data).get("data", [])
    except:
        return []

def analyze_trend(candles, max_consecutive_down=2):
    """
    正确的过滤型连续上涨：
    - 从最新往回遍历
    - 只统计真正连续的上涨
    - 遇到下跌就重新开始计数
    """
    if len(candles) < 3:
        return 0, []
    
    best_streak = 0
    current_streak = 0
    sequence = []
    
    # 从最新往回遍历
    for i in range(len(candles) - 1):
        curr = candles[i]
        prev = candles[i + 1]
        
        change_pct = (curr["close"] - prev["close"]) / prev["close"] * 100
        
        if change_pct > 0:
            # 上涨：继续当前计数
            current_streak += 1
            sequence.append(f"🔺{change_pct:.1f}%")
        else:
            # 下跌：重置计数
            if current_streak > best_streak:
                best_streak = current_streak
            current_streak = 0
            sequence = []  # 清空序列
    
    # 最后一次检查
    if current_streak > best_streak:
        best_streak = current_streak
    
    # 返回最佳的连续上涨数和对应的序列
    # 重新计算序列
    best_count = 0
    best_seq = []
    current_count = 0
    current_seq = []
    
    for i in range(len(candles) - 1):
        curr = candles[i]
        prev = candles[i + 1]
        change_pct = (curr["close"] - prev["close"]) / prev["close"] * 100
        
        if change_pct > 0:
            current_count += 1
            current_seq.append(f"🔺{change_pct:.1f}%")
        else:
            if current_count > best_count:
                best_count = current_count
                best_seq = current_seq[:]
            current_count = 0
            current_seq = []
    
    if current_count > best_count:
        best_count = current_count
        best_seq = current_seq
    
    return best_count, best_seq[::-1]  # 反转，让最新的在前面

def get_rating(up_count):
    if up_count >= 13:
        return "SS级"
    elif up_count >= 11:
        return "S级"
    elif up_count >= 9:
        return "A级"
    elif up_count >= 7:
        return "B级"
    elif up_count >= 5:
        return "C级"
    elif up_count >= 3:
        return "D级"
    return None

def load_notify_record():
    if os.path.exists(NOTIFY_FILE):
        with open(NOTIFY_FILE, "r") as f:
            return json.load(f)
    return {}

def save_notify_record(record):
    with open(NOTIFY_FILE, "w") as f:
        json.dump(record, f)

def should_notify(rating, period):
    record = load_notify_record()
    key = f"{rating}-{period}"
    import time
    now = time.time()
    
    if key in record:
        if now - record[key] < 300:
            return False
    
    record[key] = now
    save_notify_record(record)
    return True

def log_result(symbol, period, up_count, rating, sequence, current_price):
    with open(LOG_FILE, "a") as f:
        f.write(f"## {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {symbol} {period}\n")
        f.write(f"- 连续上涨: {up_count}根\n")
        f.write(f"- 评级: {rating}\n")
        f.write(f"- 当前价格: {current_price}\n")
        f.write(f"- 序列: {' '.join(sequence)}\n\n")

def send_telegram(message, chat_id=None):
    BOT_TOKEN = "8114165855:AAHC8ZETGjG_5H5vJjCFS4GaFhRvlAyocs4"
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    
    data = {
        "chat_id": chat_id if chat_id else TG_GROUP,
        "text": message
    }
    
    cmd = f'curl -s -X POST "{url}" -H "Content-Type: application/json" -d \'{json.dumps(data)}\''
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    return result.stdout

def main():
    signals = []
    
    for symbol in SYMBOLS:
        for period in PERIODS:
            candles = get_klines(symbol, period)
            if not candles:
                continue
            
            current_price = candles[0]["close"]
            up_count, sequence = analyze_trend(candles)
            rating = get_rating(up_count)
            
            log_result(symbol, period, up_count, rating, sequence, current_price)
            
            if rating and up_count >= 7 and should_notify(rating, period):
                signals.append({
                    "symbol": symbol.upper().replace("USDT", "/USDT"),
                    "period": period,
                    "rating": rating,
                    "up_count": up_count,
                    "price": current_price,
                    "sequence": " ".join(sequence)
                })
    
    if signals:
        for s in signals:
            msg = f"""📈 RIVER/USDT - {s['period'].replace('min', '分钟')}级别
评级：{s['rating']} ({s['up_count']}根连续上涨)
当前价格：{s['price']} USDT

{s['sequence']}"""
            print(f"发送通知: {msg}")
            send_telegram(msg)
    else:
        print(f"[{datetime.now().strftime('%H:%M:%S')}] 无信号")

if __name__ == "__main__":
    main()
