"""
List Matches for Sept 13, 2025 (Top Leagues)
============================================
"""

import os
import sys
import json
import psycopg2
from psycopg2.extras import RealDictCursor
from datetime import datetime

project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)

def get_clean_dsn() -> str:
    return "postgresql://suggestbet:SuGGesT2026SecuRe@localhost:15432/boilerplate_db"

def list_matches():
    print("📅 Matches on Sept 13, 2025 (Top Leagues)")
    print("="*60)

    # Load Top Leagues
    leagues_path = os.path.join(project_root, "top_leagues.json")
    try:
        with open(leagues_path, 'r') as f:
            top_leagues = json.load(f)
        league_ids = tuple(str(lid) for lid in top_leagues)
        print(f"📋 Loaded {len(top_leagues)} top leagues.")
    except Exception as e:
        print(f"❌ Error loading top_leagues.json: {e}")
        return

    # Date Range
    start_dt = datetime(2025, 9, 13, 0, 0, 0)
    end_dt = datetime(2025, 9, 13, 23, 59, 59)
    start_ts = int(start_dt.timestamp() * 1000)
    end_ts = int(end_dt.timestamp() * 1000)

    dsn = get_clean_dsn()
    conn = psycopg2.connect(dsn)
    cur = conn.cursor(cursor_factory=RealDictCursor)

    # Fetch Matches
    query = """
        SELECT m.id, m.match_name, m.home_team_id, m.away_team_id, 
               m.mst_utc, m.league_id, m.status, m.score_home, m.score_away,
               t1.name as home_team, t2.name as away_team,
               l.name as league_name
        FROM matches m
        LEFT JOIN teams t1 ON m.home_team_id = t1.id
        LEFT JOIN teams t2 ON m.away_team_id = t2.id
        LEFT JOIN leagues l ON m.league_id = l.id
        WHERE m.mst_utc BETWEEN %s AND %s
          AND m.league_id IN %s
        ORDER BY m.mst_utc ASC
    """
    
    cur.execute(query, (start_ts, end_ts, league_ids))
    rows = cur.fetchall()

    print(f"📊 Found {len(rows)} matches.")
    print("-" * 60)

    for r in rows:
        time_str = datetime.fromtimestamp(r['mst_utc']/1000).strftime('%H:%M')
        score = f"{r['score_home']} - {r['score_away']}" if r['score_home'] is not None else "v"
        status = r['status']
        
        print(f"⚽ {time_str} | {r['league_name']}")
        print(f"   {r['home_team']} {score} {r['away_team']} ({status})")
        print(f"   ID: {r['id']}")
        print("-" * 40)

    cur.close()
    conn.close()

if __name__ == "__main__":
    list_matches()
