#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NBA AI Summary Generator
Generuje podsumowania występów ulubionych graczy NBA przy użyciu Claude AI
"""

import mysql.connector
from datetime import datetime, timedelta
import anthropic
from config import DB_CONFIG, ANTHROPIC_API_KEY


class NBAPlayerTracker:
    def __init__(self):
        self.db = mysql.connector.connect(**DB_CONFIG['nba'])
        self.cursor = self.db.cursor(dictionary=True)
        self.client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
    
    def get_player_name(self, player_id):
        """Pobiera imię i nazwisko gracza"""
        self.cursor.execute("""
            SELECT first_name, last_name, team_id 
            FROM players 
            WHERE player_id = %s
        """, (player_id,))
        return self.cursor.fetchone()
    
    def get_team_name(self, team_id):
        """Pobiera nazwę drużyny"""
        self.cursor.execute("""
            SELECT full_name, abbreviation 
            FROM team_info 
            WHERE team_id = %s
        """, (team_id,))
        return self.cursor.fetchone()
    
    def get_recent_game_stats(self, player_id, days=1):
        """
        Pobiera statystyki gracza z ostatnich N dni
        """
        date_from = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
        
        query = """
            SELECT 
                pgs.*,
                g.game_date,
                g.home_team_id,
                g.away_team_id,
                g.home_team_score,
                g.away_team_score,
                g.status
            FROM player_game_stats pgs
            JOIN games g ON pgs.game_id = g.game_id
            WHERE pgs.player_id = %s
            AND g.game_date >= %s
            AND g.status = 'Final'
            ORDER BY g.game_date DESC
        """
        
        self.cursor.execute(query, (player_id, date_from))
        return self.cursor.fetchall()
    
    def format_game_data(self, player_id, stats):
        """
        Formatuje dane meczu do czytelnej formy
        """
        if not stats:
            return None
        
        stat = stats[0]  # Najnowszy mecz
        player_info = self.get_player_name(player_id)
        player_team = self.get_team_name(stat['team_id'])
        
        # Określ przeciwnika
        opponent_id = stat['away_team_id'] if stat['team_id'] == stat['home_team_id'] else stat['home_team_id']
        opponent = self.get_team_name(opponent_id)
        
        # Określ wynik dla drużyny gracza
        is_home = stat['team_id'] == stat['home_team_id']
        team_score = stat['home_team_score'] if is_home else stat['away_team_score']
        opp_score = stat['away_team_score'] if is_home else stat['home_team_score']
        result = "W" if team_score > opp_score else "L"
        
        # Oblicz FG%, 3P%, FT%
        fg_pct = round(stat['field_goals_made'] / stat['field_goals_attempted'] * 100, 1) if stat['field_goals_attempted'] > 0 else 0
        three_pct = round(stat['three_pointers_made'] / stat['three_pointers_attempted'] * 100, 1) if stat['three_pointers_attempted'] > 0 else 0
        ft_pct = round(stat['free_throws_made'] / stat['free_throws_attempted'] * 100, 1) if stat['free_throws_attempted'] > 0 else 0
        
        return {
            'player_name': f"{player_info['first_name']} {player_info['last_name']}",
            'team': player_team['full_name'],
            'team_abbr': player_team['abbreviation'],
            'opponent': opponent['full_name'],
            'opponent_abbr': opponent['abbreviation'],
            'result': result,
            'team_score': team_score,
            'opp_score': opp_score,
            'date': stat['game_date'],
            'minutes': stat['minutes_played'],
            'points': stat['points'],
            'rebounds': stat['rebounds'],
            'assists': stat['assists'],
            'steals': stat['steals'],
            'blocks': stat['blocks'],
            'turnovers': stat['turnovers'],
            'fg_made': stat['field_goals_made'],
            'fg_attempted': stat['field_goals_attempted'],
            'fg_pct': fg_pct,
            'three_made': stat['three_pointers_made'],
            'three_attempted': stat['three_pointers_attempted'],
            'three_pct': three_pct,
            'ft_made': stat['free_throws_made'],
            'ft_attempted': stat['free_throws_attempted'],
            'ft_pct': ft_pct,
            'plus_minus': stat['plus_minus']
        }
    
    def generate_ai_summary(self, game_data):
        """
        Generuje naturalne podsumowanie występu gracza przez Claude AI
        """
        prompt = f"""Jesteś komentratorem sportowym NBA. Napisz krótkie, naturalne podsumowanie występu gracza w meczu NBA.

DANE MECZU:
Gracz: {game_data['player_name']} ({game_data['team_abbr']})
Mecz: {game_data['team_abbr']} vs {game_data['opponent_abbr']}
Wynik: {game_data['team_score']}-{game_data['opp_score']} ({game_data['result']})
Data: {game_data['date']}

STATYSTYKI:
- Minuty: {game_data['minutes']}
- Punkty: {game_data['points']}
- Zbiórki: {game_data['rebounds']}
- Asysty: {game_data['assists']}
- Przechwyty: {game_data['steals']}
- Bloki: {game_data['blocks']}
- Straty: {game_data['turnovers']}
- Rzuty z gry: {game_data['fg_made']}/{game_data['fg_attempted']} ({game_data['fg_pct']}%)
- Trójki: {game_data['three_made']}/{game_data['three_attempted']} ({game_data['three_pct']}%)
- Rzuty wolne: {game_data['ft_made']}/{game_data['ft_attempted']} ({game_data['ft_pct']}%)
- +/-: {game_data['plus_minus']:+d}

WYMAGANIA:
1. Napisz 2-3 zdania po polsku
2. Użyj naturalnego języka komentarza sportowego
3. Podkreśl najważniejsze aspekty występu (dobre/słabe)
4. Wspomniij o wyniku meczu
5. Nie używaj bullet points, tylko ciągły tekst

Przykład dobrego stylu: "Kevin Durant poprowadził Suns do zwycięstwa nad Lakers 118-114, zdobywając 32 punkty przy skuteczności 60% z gry. Do tego dołożył 8 zbiórek i 5 asyst, dominując szczególnie w czwartej kwarcie gdzie zdobył 12 punktów."
"""

        message = self.client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=300,
            messages=[{
                "role": "user",
                "content": prompt
            }]
        )
        
        return message.content[0].text
    
    def get_all_summaries(self, days=1):
        """
        Generuje podsumowania dla wszystkich ulubionych graczy
        """
        summaries = []
        
        for player_id in FAVORITE_PLAYERS:
            stats = self.get_recent_game_stats(player_id, days)
            
            if not stats:
                continue
            
            game_data = self.format_game_data(player_id, stats)
            if not game_data:
                continue
            
            # Generuj AI summary
            ai_summary = self.generate_ai_summary(game_data)
            
            summaries.append({
                'player_id': player_id,
                'player_name': game_data['player_name'],
                'team': game_data['team_abbr'],
                'opponent': game_data['opponent_abbr'],
                'result': game_data['result'],
                'score': f"{game_data['team_score']}-{game_data['opp_score']}",
                'date': game_data['date'],
                'stats': {
                    'minutes': game_data['minutes'],
                    'points': game_data['points'],
                    'rebounds': game_data['rebounds'],
                    'assists': game_data['assists'],
                    'fg': f"{game_data['fg_made']}/{game_data['fg_attempted']}",
                    'fg_pct': game_data['fg_pct'],
                    'three': f"{game_data['three_made']}/{game_data['three_attempted']}",
                    'plus_minus': game_data['plus_minus']
                },
                'ai_summary': ai_summary,
                'full_data': game_data
            })
        
        return summaries
    
    def close(self):
        self.cursor.close()
        self.db.close()


if __name__ == "__main__":
    # Test
    tracker = NBAPlayerTracker()
    summaries = tracker.get_all_summaries(days=2)
    
    print(f"\n🏀 NBA Player Summaries ({len(summaries)} graczy)\n")
    print("=" * 80)
    
    for summary in summaries:
        print(f"\n{summary['player_name']} ({summary['team']})")
        print(f"vs {summary['opponent']} • {summary['score']} ({summary['result']}) • {summary['date']}")
        print(f"📊 {summary['stats']['points']} PTS | {summary['stats']['rebounds']} REB | {summary['stats']['assists']} AST")
        print(f"\n{summary['ai_summary']}")
        print("-" * 80)
    
    tracker.close()