import pymysql
import datetime
import random

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '31031992',
    'database': 'dating_fans',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

def settle_big_small():
    # --- 替代 pytz 的时区处理方案 ---
    # 获取当前 UTC 时间并手动加 8 小时得到北京时间
    bj_time_obj = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    now = bj_time_obj.strftime('%Y-%m-%d %H:%M:%S')
    
    conn = pymysql.connect(**db_config)
    try:
        with conn.cursor() as cursor:
            # 强制设置 MySQL 会话时区为东八区
            cursor.execute("SET time_zone = '+8:00'")
            
            # --- 第一步：自动开奖 (补齐遗漏的 winner) ---
            # 寻找已经到开奖时间，但还没有 winner 结果的期数并随机生成结果
            cursor.execute("""
                UPDATE bs_game_results 
                SET winner = IF(RAND() > 0.5, 'Big', 'Small'), is_processed = 1 
                WHERE open_time <= %s AND winner IS NULL
            """, (now,))
            conn.commit() # 立即提交开奖结果，确保下面的查询能查到

            # --- 第二步：查找待结算的投注 ---
            # 关联 bs_votes 和 bs_game_results 找出中奖者
            sql = """
                SELECT v.id, v.uid, v.points, v.option_value, g.winner, v.session_id 
                FROM bs_votes v
                JOIN bs_game_results g ON v.session_id = g.session_id
                WHERE v.is_settled = 0 
                  AND g.open_time <= %s 
                  AND g.winner IS NOT NULL
            """
            cursor.execute(sql, (now,))
            records = cursor.fetchall()

            if not records:
                print(f"[{now}] No pending votes to settle.")
                return

            # --- 第三步：循环处理金额 (关键点：处理一笔提交一笔) ---
            for rec in records:
                try:
                    if rec['option_value'] == rec['winner']:
                        # 中奖翻倍 (赔率 2.0)
                        payout = float(rec['points']) * 1.2
                        # 更新用户余额
                        cursor.execute(
                            "UPDATE users SET balance = balance + %s WHERE id = %s", 
                            (payout, rec['uid'])
                        )
                        print(f"WIN: Session {rec['session_id']} - User {rec['uid']} won {payout}")
                    else:
                        print(f"LOSE: Session {rec['session_id']} - User {rec['uid']} lost")

                    # 无论输赢，都标记该注单已结算
                    cursor.execute("UPDATE bs_votes SET is_settled = 1 WHERE id = %s", (rec['id'],))
                    
                    # 每一条注单处理完立刻 commit，用户刷新页面就能立刻看到钱变动
                    conn.commit()
                    
                except Exception as inner_e:
                    conn.rollback() # 单条失败只回滚单条
                    print(f"Error processing record ID {rec['id']}: {inner_e}")
            
            print(f"[{now}] All done. Processed {len(records)} records.")

    except Exception as e:
        conn.rollback()
        print(f"Main System Error: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    settle_big_small()