#!/usr/bin/env python3
"""
Cron nocturne - Met à jour les paris avec les résultats PMU
Usage: python3 update_results_cron.py
Cron: 0 20 * * * (après les résultats PMU)
"""

import sqlite3
import subprocess
import sys
from datetime import datetime, timedelta

DB_PATH = "/home/h3r7/turf_scraper/turf.db"
LOG_FILE = "/home/h3r7/turf_scraper/logs/update_results.log"


def log(msg: str):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{timestamp}] {msg}"
    print(line)
    with open(LOG_FILE, "a") as f:
        f.write(line + "\n")


def fetch_pmu_results(date: str):
    """Récupère les résultats PMU via pmu_results.py"""
    log(f"Fetching PMU results for {date}...")

    cmd = f"cd /home/h3r7/turf_scraper && python3 pmu_results.py --date {date}"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

    if result.returncode == 0:
        log(f"PMU results fetched successfully")
        return True
    else:
        log(f"PMU results fetch failed: {result.stderr}")
        return False


def update_paris(date: str):
    """Met à jour les paris avec les résultats"""
    log(f"Updating paris for {date}...")

    cmd = f"cd /home/h3r7/turf_scraper && python3 update_paris_results.py --date {date}"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

    if result.returncode == 0:
        log(f"Paris updated: {result.stdout.strip()}")
        return True
    else:
        log(f"Paris update failed: {result.stderr}")
        return False


def main():
    log("=" * 50)
    log("🌙 UPDATE RESULTS CRON - DEMARRAGE")
    log("=" * 50)

    today = datetime.now().strftime("%Y-%m-%d")

    # 1. Fetch PMU results
    fetch_pmu_results(today)

    # 2. Update paris
    update_paris(today)

    # 3. Also update yesterday if needed (backup)
    yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
    update_paris(yesterday)

    log("=" * 50)
    log("✅ UPDATE RESULTS - TERMINÉ")
    log("=" * 50)


if __name__ == "__main__":
    main()
