#!/usr/bin/env python3
"""Check finished football matches with odds"""

import sys
sys.path.insert(0, 'ai-engine')

import psycopg2
from psycopg2.extras import RealDictCursor
from datetime import datetime, timezone

# Read .env file manually
db_url = None
with open('.env') as f:
    for line in f:
        if line.startswith('DATABASE_URL'):
            db_url = line.split('=', 1)[1].strip().strip('"').strip("'")
            break

if '?schema=' in db_url:
    db_url = db_url.split('?schema=')[0]

conn = psycopg2.connect(db_url)
cur = conn.cursor(cursor_factory=RealDictCursor)

# Get matches with odds data
cur.execute('''
SELECT 
    m.id, m.score_home, m.score_away, m.ht_score_home, m.ht_score_away,
    m.mst_utc,
    ht.name as home_team_name,
    at.name as away_team_name,
    l.name as league_name,
    o.ms_h, o.ms_d, o.ms_a
FROM matches m
JOIN teams ht ON ht.id = m.home_team_id
JOIN teams at ON at.id = m.away_team_id
JOIN leagues l ON l.id = m.league_id
LEFT JOIN odds o ON o.match_id = m.id
WHERE l.sport = 'football'
AND m.score_home IS NOT NULL
AND o.ms_h IS NOT NULL
ORDER BY m.mst_utc DESC
LIMIT 30
''')

matches = cur.fetchall()
print('Last 30 finished football matches with odds:')
print()

for m in matches:
    ts = m['mst_utc'] / 1000
    dt = datetime.fromtimestamp(ts, tz=timezone.utc)
    score = 'HT: {}-{}, FT: {}-{}'.format(m['ht_score_home'], m['ht_score_away'], m['score_home'], m['score_away'])
    odds = 'Odds: H={:.2f} D={:.2f} A={:.2f}'.format(float(m['ms_h'] or 0), float(m['ms_d'] or 0), float(m['ms_a'] or 0))
    league = (m['league_name'] or 'Unknown')[:15]
    home = (m['home_team_name'] or 'Unknown')[:15]
    away = (m['away_team_name'] or 'Unknown')[:15]
    print('{} | {:15} | {:15} vs {:15} | {} | {}'.format(dt.strftime('%Y-%m-%d %H:%M'), league, home, away, score, odds))

cur.close()
conn.close()
