#!/usr/bin/env python3
"""
Track Injury Status Changes

Monitors PlayerInjury table for status changes and records history.
Useful for analyzing how injury designation changes affect lines.

Run: Every 2-4 hours
"""
import psycopg2
import os
from datetime import datetime, timezone


def load_db_url():
    env_path = '/var/www/html/eventheodds/.env'
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if line.startswith('SPORTS_DATABASE_URL='):
                    return line.split('=', 1)[1].strip().strip('"').split('?')[0]
    except FileNotFoundError:
        pass
    return os.environ.get('SPORTS_DATABASE_URL', '').split('?')[0]


def run_tracking():
    print("=" * 60)
    print("TRACK INJURY STATUS CHANGES")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

    db_url = load_db_url()
    conn = psycopg2.connect(db_url)
    cur = conn.cursor()

    # Get current injuries with their last known status
    print("\n[1] Loading current injuries...")
    cur.execute('''
        SELECT
            pi.id,
            pi.league,
            pi."playerExternalId",
            pi."playerName",
            pi.status,
            pi."updatedAt",
            (
                SELECT "newStatus"
                FROM "InjuryStatusHistory" ish
                WHERE ish."injuryId" = pi.id
                ORDER BY "statusChangedAt" DESC
                LIMIT 1
            ) as last_recorded_status
        FROM "PlayerInjury" pi
        WHERE pi.league IN ('nba', 'nfl', 'nhl')
    ''')
    injuries = cur.fetchall()
    print(f"  Found {len(injuries)} active injury records")

    # Track status changes
    print("\n[2] Detecting status changes...")
    changes = []

    for injury in injuries:
        inj_id, league, player_id, name, current_status, updated_at, last_status = injury

        # If no history exists, record initial status
        if last_status is None:
            changes.append({
                'injury_id': inj_id,
                'league': league,
                'player_id': player_id,
                'name': name,
                'prev_status': None,
                'new_status': current_status,
                'type': 'initial'
            })
        # If status changed, record the change
        elif current_status != last_status:
            changes.append({
                'injury_id': inj_id,
                'league': league,
                'player_id': player_id,
                'name': name,
                'prev_status': last_status,
                'new_status': current_status,
                'type': 'change'
            })

    print(f"  Found {len(changes)} status changes to record")

    if not changes:
        print("  No new changes to record")
        cur.close()
        conn.close()
        return {'changes': 0}

    # Find upcoming games for affected players
    print("\n[3] Linking to upcoming games...")
    for change in changes:
        # Find team for this player
        cur.execute('''
            SELECT team FROM "PlayerInjury"
            WHERE "playerExternalId" = %s AND league = %s
        ''', (change['player_id'], change['league']))
        team_row = cur.fetchone()
        team = team_row[0] if team_row else None

        if team:
            # Find next game for this team
            cur.execute('''
                SELECT id, "gameDate"
                FROM "SportsGame"
                WHERE league = %s
                  AND ("homeTeam" = %s OR "awayTeam" = %s)
                  AND "gameDate" > NOW()
                  AND "homeScore" IS NULL
                ORDER BY "gameDate"
                LIMIT 1
            ''', (change['league'], team, team))
            game = cur.fetchone()

            if game:
                change['game_id'] = game[0]
                change['game_date'] = game[1]

                # Calculate hours before game
                now = datetime.now(timezone.utc)
                game_dt = game[1].replace(tzinfo=timezone.utc) if game[1].tzinfo is None else game[1]
                change['hours_before'] = (game_dt - now).total_seconds() / 3600
            else:
                change['game_id'] = None
                change['game_date'] = None
                change['hours_before'] = None
        else:
            change['game_id'] = None
            change['game_date'] = None
            change['hours_before'] = None

    # Insert history records
    print("\n[4] Recording status history...")
    for change in changes:
        cur.execute('''
            INSERT INTO "InjuryStatusHistory" (
                "injuryId", league, "playerExternalId", "playerName",
                "previousStatus", "newStatus", "hoursBeforeGame",
                "gameId", "gameDate"
            )
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        ''', (
            change['injury_id'],
            change['league'],
            change['player_id'],
            change['name'],
            change['prev_status'],
            change['new_status'],
            change.get('hours_before'),
            change.get('game_id'),
            change.get('game_date')
        ))

    conn.commit()

    # Report significant changes
    print("\n[5] Significant status changes:")
    sig_changes = [c for c in changes if c['type'] == 'change']
    for c in sig_changes[:10]:
        print(f"  {c['name']} ({c['league']}): {c['prev_status']} → {c['new_status']}")
        if c.get('hours_before'):
            print(f"    {c['hours_before']:.1f} hours before game")

    print(f"\n{'='*60}")
    print(f"Recorded {len(changes)} status entries ({len(sig_changes)} changes)")
    print("=" * 60)

    cur.close()
    conn.close()

    return {'changes': len(changes), 'status_changes': len(sig_changes)}


if __name__ == '__main__':
    run_tracking()
