
import os
import psycopg2
from psycopg2.extras import RealDictCursor

def inspect_deep_intersection():
    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)
        
        print("\n🔍 DEEP DATA INTERSECTION CHECK\n")

        # 1. Base: Scored Football Matches
        base_query_from = "FROM matches m"
        base_query_where = "WHERE m.sport='football' AND m.score_home IS NOT NULL"
        cursor.execute(f"SELECT COUNT(*) as count {base_query_from} {base_query_where}")
        total = cursor.fetchone()['count']
        print(f"Total Scored Matches: {total:,}")

        # 2. Check Individual Coverage
        tables = {
            "Team Stats": "JOIN match_team_stats s ON m.id = s.match_id",
            "Player Events": "JOIN match_player_events e ON m.id = e.match_id",
            "Odds": "JOIN odd_categories oc ON m.id = oc.match_id",
            "Officials (Referees)": "JOIN match_officials mo ON m.id = mo.match_id",
            "Player Stats (Detailed)": "JOIN match_player_stats ps ON m.id = ps.match_id"
        }

        for name, join_clause in tables.items():
            cursor.execute(f"SELECT COUNT(DISTINCT m.id) as count {base_query_from} {join_clause} {base_query_where}")
            count = cursor.fetchone()['count']
            print(f"With {name}: {count:,} ({count/total*100:.1f}%)")

        # 3. The User's "All-in-One" Question (Golden 28k + Officials)
        print("\n--- Intersections ---")
        
        # Previous Golden (Stats + Events + Odds)
        cursor.execute(f"""
            SELECT COUNT(DISTINCT m.id) as count {base_query_from} 
            JOIN match_team_stats s ON m.id = s.match_id
            JOIN match_player_events e ON m.id = e.match_id
            JOIN odd_categories oc ON m.id = oc.match_id
            {base_query_where}
        """)
        golden = cursor.fetchone()['count']
        print(f"Golden (Stats + Events + Odds): {golden:,}")

        # Golden + Officials
        cursor.execute(f"""
            SELECT COUNT(DISTINCT m.id) as count {base_query_from} 
            JOIN match_team_stats s ON m.id = s.match_id
            JOIN match_player_events e ON m.id = e.match_id
            JOIN odd_categories oc ON m.id = oc.match_id
            JOIN match_officials mo ON m.id = mo.match_id
            {base_query_where}
        """)
        platinum = cursor.fetchone()['count']
        print(f"Platinum (Golden + Officials): {platinum:,}")

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

if __name__ == "__main__":
    inspect_deep_intersection()
