#!/usr/bin/env python3
"""Fix and explain RTF calculation."""

import os
import sys
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

from supabase import create_client

sb = create_client(os.environ['URL'], os.environ['SUPABASE_ADMIN'])

print("=" * 70)
print("RTF CALCULATION - CORRECTED")
print("=" * 70)

# Get heartbeats for wall time calculation
result = sb.table('worker_heartbeats').select('session_start, last_heartbeat, session_audio_minutes, session_videos_done').execute()
workers = result.data or []

if workers:
    # Parse timestamps
    starts = []
    ends = []
    for w in workers:
        if w.get('session_start'):
            starts.append(datetime.fromisoformat(w['session_start'].replace('Z', '+00:00')))
        if w.get('last_heartbeat'):
            ends.append(datetime.fromisoformat(w['last_heartbeat'].replace('Z', '+00:00')))

    if starts and ends:
        wall_start = min(starts)
        wall_end = max(ends)
        wall_time_sec = (wall_end - wall_start).total_seconds()
        wall_time_min = wall_time_sec / 60

        total_audio_min = sum(w.get('session_audio_minutes', 0) for w in workers)
        total_videos = sum(w.get('session_videos_done', 0) for w in workers)
        num_gpus = len(workers)

        print(f"\n📊 SESSION STATS:")
        print(f"   Start: {wall_start.strftime('%H:%M:%S')}")
        print(f"   End:   {wall_end.strftime('%H:%M:%S')}")
        print(f"   Wall time: {wall_time_min:.1f} min ({wall_time_sec/3600:.2f} hours)")
        print(f"   GPUs: {num_gpus}")
        print(f"   Videos processed: {total_videos}")
        print(f"   Audio processed: {total_audio_min:.1f} min ({total_audio_min/60:.2f} hours)")

        # RTF calculations
        cluster_rtf = total_audio_min / wall_time_min if wall_time_min > 0 else 0
        per_gpu_rtf = cluster_rtf / num_gpus if num_gpus > 0 else 0

        print(f"\n📈 RTF (Real-Time Factor):")
        print(f"   🚀 CLUSTER RTF: {cluster_rtf:.0f}x real-time")
        print(f"      (processed {total_audio_min:.0f} min audio in {wall_time_min:.1f} min wall time)")
        print(f"   📟 Per-GPU RTF: {per_gpu_rtf:.1f}x")
        print(f"      (average throughput per individual GPU)")

        # Explanation
        print(f"\n💡 EXPLANATION:")
        print(f"   The previous 44x was per-GPU RTF (cumulative processing time / audio)")
        print(f"   The true cluster RTF = audio / wall_time = {cluster_rtf:.0f}x")
        print(f"   With {num_gpus} GPUs running in parallel, cluster RTF ≈ {num_gpus} × per-GPU RTF")

print("\n" + "=" * 70)
