
import os
import psycopg2
from psycopg2.extras import RealDictCursor
import pandas as pd

MATCH_ID = '3jv3r7dd46nx6cnmpqq9d4x9m'

def analyze_win():
    try:
        db_url = os.environ.get('DATABASE_URL', 'postgresql://suggestbet:SuGGesT2026SecuRe@localhost:15432/boilerplate_db')
        conn = psycopg2.connect(db_url)
        cursor = conn.cursor(cursor_factory=RealDictCursor)
        
        # 1. Search for High Odds Match
        print("🔍 Searching for matches with Odds > 17.0 in the last 7 days...")
        cursor.execute("""
            SELECT 
                m.id, m.mst_utc, 
                m.score_home, m.score_away,
                m.home_team_id, m.away_team_id,
                ht.name as home_team, at.name as away_team,
                l.name as league,
                os.odd_value, os.name as selection
            FROM matches m
            JOIN teams ht ON m.home_team_id = ht.id
            JOIN teams at ON m.away_team_id = at.id
            JOIN leagues l ON m.league_id = l.id
            JOIN odd_categories oc ON m.id = oc.match_id
            JOIN odd_selections os ON oc.db_id = os.odd_category_db_id
            WHERE m.sport = 'football'
              AND m.score_home IS NOT NULL
              AND oc.name = 'Maç Sonucu'
              AND os.odd_value::numeric > 14.0
              AND m.mst_utc > (EXTRACT(EPOCH FROM NOW()) * 1000 - 7 * 24 * 60 * 60 * 1000)
            ORDER BY m.mst_utc DESC
        """)
        
        matches = cursor.fetchall()
        
        target_match = None
        for m in matches:
            # Check if this high odd actually won
            sel = m['selection']
            won = False
            if sel == '1' and m['score_home'] > m['score_away']: won = True
            if sel == '2' and m['score_away'] > m['score_home']: won = True
            
            if won:
                target_match = m
                break
        
        if not target_match:
            print("No high odds WIN found in the last 7 days.")
            return

        print(f"\n🏆 THE MIRACLE MATCH FOUND: {target_match['id']} 🏆")
        print(f"League: {target_match['league']}")
        print(f"Match:  {target_match['home_team']} vs {target_match['away_team']}")
        print(f"Score:  {target_match['score_home']} - {target_match['score_away']}")
        print(f"Bet:    {target_match['selection']} (Odds: {target_match['odd_value']})")
        
        # Analyze Form
        print(f"\n📜 {target_match['home_team']} Recent Form:")
        cursor.execute("""
            SELECT score_home, score_away 
            FROM matches 
            WHERE (home_team_id = %s OR away_team_id = %s) AND mst_utc < %s
            ORDER BY mst_utc DESC LIMIT 5
        """, (target_match['home_team_id'], target_match['home_team_id'], target_match['mst_utc']))
        for gm in cursor.fetchall():
            print(f"   {gm['score_home']}-{gm['score_away']}")

        print(f"\n📜 {target_match['away_team']} Recent Form:")
        cursor.execute("""
            SELECT score_home, score_away 
            FROM matches 
            WHERE (home_team_id = %s OR away_team_id = %s) AND mst_utc < %s
            ORDER BY mst_utc DESC LIMIT 5
        """, (target_match['away_team_id'], target_match['away_team_id'], target_match['mst_utc']))
        for gm in cursor.fetchall():
            print(f"   {gm['score_home']}-{gm['score_away']}")
            
        # 3. Odds Check
        cursor.execute("""
            SELECT os.name, os.odd_value 
            FROM odd_categories oc
            JOIN odd_selections os ON oc.db_id = os.odd_category_db_id
            WHERE oc.match_id = %s AND oc.name = 'Maç Sonucu'
        """, (MATCH_ID,))
        print("\n💰 Odds Table:")
        for odd in cursor.fetchall():
            print(f"   {odd['name']}: {odd['odd_value']}")

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

if __name__ == "__main__":
    analyze_win()
