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

MATCH_ID = '8hlli3zuh2q05utzcjmkca8lw' # Watford vs Portsmouth

def check_form():
    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. Get Match Info
        cursor.execute("""
            SELECT m.home_team_id, m.away_team_id, m.mst_utc, 
                   ht.name as home_name, at.name as away_name
            FROM matches m
            JOIN teams ht ON m.home_team_id = ht.id
            JOIN teams at ON m.away_team_id = at.id
            WHERE m.id = %s
        """, (MATCH_ID,))
        
        match = cursor.fetchone()
        if not match:
            print("Match not found")
            return
            
        print(f"Match: {match['home_name']} vs {match['away_name']}")
        print(f"Date: {datetime.fromtimestamp(match['mst_utc']/1000).strftime('%Y-%m-%d %H:%M')}")
        
        # 2. Function to get relative form
        def get_team_form(team_id, team_name, match_date_ms):
            print(f"\n📜 {team_name} Last 5 Matches BEFORE this game:")
            cursor.execute("""
                SELECT 
                    m.id, m.mst_utc, 
                    m.score_home, m.score_away,
                    m.home_team_id, m.away_team_id,
                    t_opp.name as opponent_name
                FROM matches m
                JOIN teams t_opp ON (
                    CASE 
                        WHEN m.home_team_id = %s THEN m.away_team_id 
                        ELSE m.home_team_id 
                    END = t_opp.id
                )
                WHERE (m.home_team_id = %s OR m.away_team_id = %s)
                  AND m.mst_utc < %s
                  AND m.score_home IS NOT NULL
                ORDER BY m.mst_utc DESC
                LIMIT 5
            """, (team_id, team_id, team_id, match_date_ms))
            
            rows = cursor.fetchall()
            for r in rows:
                is_home = (r['home_team_id'] == team_id)
                goals_for = r['score_home'] if is_home else r['score_away']
                goals_against = r['score_away'] if is_home else r['score_home']
                
                result = "DRAW"
                if goals_for > goals_against: result = "WIN"
                if goals_for < goals_against: result = "LOSS"
                
                loc = "(H)" if is_home else "(A)"
                date_str = datetime.fromtimestamp(r['mst_utc']/1000).strftime('%d/%m')
                
                print(f"   {date_str} vs {r['opponent_name'][:15]} {loc}: {goals_for}-{goals_against} [{result}]")

        get_team_form(match['home_team_id'], match['home_name'], match['mst_utc'])
        get_team_form(match['away_team_id'], match['away_name'], match['mst_utc'])

    except Exception as e:
        print(e)

if __name__ == "__main__":
    check_form()
