#!/usr/bin/env python3
"""
Compare All Predictions (Our + External Sources)
"""
import sqlite3
from datetime import datetime
from collections import defaultdict

DB_PATH = "/home/h3r7/turf_scraper/turf.db"

def compare_all(date):
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    
    print(f"\n{'='*60}")
    print(f"COMPARAISON COMPLÈTE - {date}")
    print(f"{'='*60}")
    
    # Our predictions
    print("\n[NOTRE SYSTÈME]")
    c.execute("SELECT horse_name, odds, prediction_rank FROM predictions WHERE date = ? ORDER BY prediction_rank", (date,))
    our_preds = c.fetchall()
    for name, odds, rank in our_preds:
        print(f"  {rank}. {name} ({odds})")
    
    # External predictions grouped by source
    c.execute("SELECT DISTINCT source FROM external_predictions WHERE date = ?", (date,))
    sources = [r[0] for r in c.fetchall()]
    
    for source in sources:
        print(f"\n[{source.upper()}]")
        c.execute("SELECT horse_name, odds, rank, confidence FROM external_predictions WHERE date = ? AND source = ? ORDER BY rank", (date, source))
        preds = c.fetchall()
        for name, odds, rank, conf in preds:
            conf_str = f" ({conf}%)" if conf else ""
            print(f"  {rank}. {name} ({odds}){conf_str}")
    
    # Results
    print("\n[RÉSULTATS]")
    c.execute("SELECT horse_name, position FROM results WHERE date = ? AND position <= 5", (date,))
    results = c.fetchall()
    for name, pos in results:
        print(f"  {pos}. {name}")
    
    # Score
    if results:
        result_names = [r[0] for r in results]
        
        print(f"\n[SCORE - 3 premiers]")
        
        # Our system
        our_hits = sum(1 for p in our_preds if p[0] in result_names[:3])
        print(f"  Nous: {our_hits}/3")
        
        # Each source
        for source in sources:
            c.execute("SELECT horse_name FROM external_predictions WHERE date = ? AND source = ? ORDER BY rank", (date, source))
            preds = [r[0] for r in c.fetchall()]
            hits = sum(1 for p in preds if p in result_names[:3])
            print(f"  {source}: {hits}/3")
    
    conn.close()

def add_external(date, source, race_name, horse_name, odds, rank, confidence=None):
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute('''
        INSERT INTO external_predictions (date, source, race_name, horse_name, odds, rank, confidence)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ''', (date, source, race_name, horse_name, odds, rank, confidence))
    conn.commit()
    conn.close()

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        compare_all(sys.argv[1])
    else:
        compare_all(datetime.now().strftime('%Y-%m-%d'))
