#!/usr/bin/env python3
"""
Test script to verify bet cancellation logic
"""

import sqlite3
import json
from datetime import datetime

def check_database():
    """Check what's in the database"""
    from mbetterclient.config.settings import get_user_data_dir
    db_path = get_user_data_dir() / "mbetterclient.db"
    conn = sqlite3.connect(str(db_path))
    cursor = conn.cursor()

    # Check table names
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = cursor.fetchall()
    print(f"Tables in database: {[t[0] for t in tables]}")

    # Check bets
    try:
        cursor.execute("SELECT uuid, fixture_id, paid FROM bets LIMIT 5")
        bets = cursor.fetchall()
        print(f"\nFound {len(bets)} bets:")
        for bet in bets:
            print(f"  UUID: {bet[0]}, Fixture: {bet[1]}, Paid: {bet[2]}")

        # Check bet details for first bet
        if bets:
            bet_uuid = bets[0][0]
            cursor.execute("SELECT id, bet_id, match_id, outcome, amount, result FROM bets_details WHERE bet_id = ?", (bet_uuid,))
            details = cursor.fetchall()
            print(f"\nBet details for {bet_uuid}:")
            for detail in details:
                print(f"  ID: {detail[0]}, Match: {detail[2]}, Outcome: {detail[3]}, Amount: {detail[4]}, Result: {detail[5]}")

            # Check match statuses for this bet
            match_ids = [detail[2] for detail in details]
            if match_ids:
                placeholders = ','.join('?' * len(match_ids))
                cursor.execute(f"SELECT id, status FROM matches WHERE id IN ({placeholders})", match_ids)
                match_statuses = cursor.fetchall()
                print(f"\nMatch statuses for bet {bet_uuid}:")
                for match_id, status in match_statuses:
                    print(f"  Match {match_id}: {status}")
    except sqlite3.OperationalError as e:
        print(f"\nError querying bets table: {e}")

    # Check matches
    try:
        cursor.execute("SELECT id, match_number, status, fixture_id FROM matches ORDER BY id LIMIT 10")
        matches = cursor.fetchall()
        print(f"\nFound {len(matches)} matches (showing first 10):")
        for match in matches:
            print(f"  ID: {match[0]}, Number: {match[1]}, Status: {match[2]}, Fixture: {match[3]}")

        # Count matches by status
        cursor.execute("SELECT status, COUNT(*) FROM matches GROUP BY status ORDER BY COUNT(*) DESC")
        status_counts = cursor.fetchall()
        print(f"\nMatch status counts:")
        for status, count in status_counts:
            print(f"  {status}: {count}")

        # Check total matches
        cursor.execute("SELECT COUNT(*) FROM matches")
        total_matches = cursor.fetchone()[0]
        print(f"\nTotal matches in database: {total_matches}")
    except sqlite3.OperationalError as e:
        print(f"\nError querying matches table: {e}")

    conn.close()

if __name__ == "__main__":
    check_database()