#!/usr/bin/env python3
"""
TurfFish Bridge - Connect Turf Scraper à MiroFish
"""
import sqlite3
import json
import os
from datetime import datetime, date
from pathlib import Path

DB_PATH = "/home/h3r7/turf_scraper/turf.db"
OUTPUT_DIR = "/home/h3r7/MiroFish/docs/turf_data"

def get_upcoming_races(days_ahead=1):
    """Récupère les courses à venir depuis la DB"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    
    today = date.today().isoformat()
    from datetime import timedelta
    future = (date.today() + timedelta(days=days_ahead)).isoformat()
    
    c.execute("""
        SELECT DISTINCT date, race_name, race_hippodrome, race_time 
        FROM predictions 
        WHERE date >= ? AND date <= ?
        ORDER BY date, race_time
    """, (today, future))
    
    races = c.fetchall()
    conn.close()
    return races

def get_race_details(race_date, race_name):
    """Récupère les détails d'une course (chevaux, cotes, pronostics)"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    
    # Predictions pour cette course
    c.execute("""
        SELECT horse_number, horse_name, odds, prediction_rank, source
        FROM predictions
        WHERE date = ? AND race_name = ?
        ORDER BY prediction_rank
    """, (race_date, race_name))
    
    horses = c.fetchall()
    
    # Résultats existants (si course passée)
    c.execute("""
        SELECT position, horse_name, odds
        FROM results
        WHERE date = ? AND race_name = ?
        ORDER BY position
    """, (race_date, race_name))
    
    results = c.fetchall()
    conn.close()
    
    return {
        "predictions": [dict(h) for h in horses],
        "results": [dict(r) for r in results] if results else None
    }

def generate_mirofish_input(race_date, race_name, race_hippodrome, race_time, horses):
    """Génère un fichier Markdown compatible MiroFish"""
    
    markdown = f"""# Course du {race_date} - {race_name}

## Informations

- **Date**: {race_date}
- **Hippodrome**: {race_hippodrome}
- **Heure**: {race_time}

## Chevaux partants

"""
    for h in horses:
        rank = h.get('prediction_rank', '')
        name = h.get('horse_name', '')
        odds = h.get('odds', 'N/A')
        number = h.get('horse_number', '')
        source = h.get('source', '')
        
        markdown += f"### {number}. {name}\n"
        if rank:
            markdown += f"- **Classement prédit**: {rank}e choix\n"
        if odds and odds != 'N/A':
            markdown += f"- **Cote**: {odds}\n"
        if source:
            markdown += f"- **Source**: {source}\n"
        markdown += "\n"
    
    # Ajouter contexte marché
    markdown += """## Contexte des parieurs

Les parieurs hippiques suivent généralement:
- Les pronostics des tipsters professionnels
- Les cotes des bookmakers
- La forme récente des chevaux
- Les statistiques jockeys/entraineurs

## Objectif de prédiction

Prédire:
1. Le favori probable basé sur les cotes et pronostics
2. Les outsiders intéressante pour les places
3. La réaction du "marché" (parieurs) à cette course
"""
    
    return markdown

def export_races_to_mirofish(days_ahead=1):
    """Exporte les courses à venir vers des fichiers MiroFish"""
    
    # Créer le dossier de sortie
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    races = get_upcoming_races(days_ahead)
    
    if not races:
        print("Aucune course à venir trouvée")
        return
    
    print(f"Exported {len(races)} courses")
    
    for race in races:
        race_date = race['date']
        race_name = race['race_name']
        race_hippodrome = race['race_hippodrome']
        race_time = race['race_time']
        
        # Récupérer les détails
        details = get_race_details(race_date, race_name)
        horses = details['predictions']
        
        if not horses:
            print(f"Pas de pronostics pour {race_name}")
            continue
        
        # Générer le fichier Markdown
        content = generate_mirofish_input(
            race_date, race_name, race_hippodrome, race_time, horses
        )
        
        # Nom de fichier safe
        safe_name = f"{race_date}_{race_name.replace(' ', '_')[:30]}.md"
        filepath = os.path.join(OUTPUT_DIR, safe_name)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"✓ {safe_name}")

if __name__ == "__main__":
    export_races_to_mirofish(days_ahead=2)