#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os

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

from flask import Flask, jsonify, send_file, request
from flask_cors import CORS
import mysql.connector
import json
from datetime import datetime, timedelta
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from anthropic import Anthropic
import config

app = Flask(__name__)
app.config['SECRET_KEY'] = config.SECRET_KEY
CORS(app, resources={r"/api/*": {"origins": "*"}})

# =========================
# FUNKCJE POMOCNICZE
# =========================

def get_db_connection():
    """Połączenie z bazą MySQL (SQM)"""
    return mysql.connector.connect(
        host=config.DB_HOST,
        user=config.DB_USER,
        password=config.DB_PASSWORD,
        database=config.DB_NAME,
        charset='utf8mb4'
    )

def get_nba_db_connection():
    """Połączenie z bazą MySQL (NBA)"""
    if hasattr(config, 'NBA_DB_NAME') and config.NBA_DB_NAME:
        return mysql.connector.connect(
            host=config.NBA_DB_HOST,
            user=config.NBA_DB_USER,
            password=config.NBA_DB_PASSWORD,
            database=config.NBA_DB_NAME,
            charset='utf8mb4'
        )
    else:
        return get_db_connection()

def get_jarvis_db_connection():
    """Połączenie z bazą Jarvis (emaile, akcje, reguły)"""
    return mysql.connector.connect(
        host=config.JARVIS_DB_HOST,
        user=config.JARVIS_DB_USER,
        password=config.JARVIS_DB_PASSWORD,
        database=config.JARVIS_DB_NAME,
        charset='utf8mb4'
    )

# =========================
# ENDPOINT: EMAILE - LISTA
# =========================

@app.route('/api/emails/latest', methods=['GET'])
def get_latest_emails():
    """Zwraca listę najnowszych emaili z audio"""
    try:
        output_dir = config.OUTPUT_DIR
        files = []
        
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
            
        for filename in os.listdir(output_dir):
            if filename.endswith('.json'):
                filepath = os.path.join(output_dir, filename)
                with open(filepath, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    audio_filename = os.path.basename(data['audio_file'])
                    data['audio_url'] = f"http://85.194.240.29:5001/api/emails/audio/{audio_filename}"
                    files.append(data)
        
        files.sort(key=lambda x: x['timestamp'], reverse=True)
        
        return jsonify({
            'success': True,
            'count': len(files),
            'emails': files[:20]
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/emails/audio/<filename>', methods=['GET'])
def get_audio_file(filename):
    """Zwraca plik audio MP3"""
    try:
        filepath = os.path.join(config.OUTPUT_DIR, filename)
        if os.path.exists(filepath) and filename.endswith('.mp3'):
            return send_file(filepath, mimetype='audio/mpeg')
        return jsonify({'error': 'File not found'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# =========================
# ENDPOINT: PEŁNA TREŚĆ EMAILA
# =========================

@app.route('/api/emails/<uid>/full', methods=['GET'])
def get_email_full(uid):
    """Zwraca pełną treść emaila z bazy danych"""
    try:
        conn = get_jarvis_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT id, email_uid, sender_email, sender_name, subject,
                   body_text, body_html, category, priority, received_at
            FROM email_history
            WHERE email_uid = %s
            ORDER BY received_at DESC
            LIMIT 1
        """
        
        cursor.execute(query, (uid,))
        email_data = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        if not email_data:
            return jsonify({'success': False, 'error': 'Email not found'}), 404
        
        # Formatuj datę
        if email_data['received_at']:
            email_data['received_at'] = email_data['received_at'].strftime('%Y-%m-%d %H:%M:%S')
        
        return jsonify({
            'success': True,
            'email': email_data
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: SUGEROWANA ODPOWIEDŹ
# =========================

@app.route('/api/emails/<uid>/suggest-reply', methods=['POST'])
def suggest_reply(uid):
    """Generuje 3 sugerowane odpowiedzi używając Claude"""
    try:
        # Pobierz email z bazy
        conn = get_jarvis_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT sender_email, sender_name, subject, body_text, body_html
            FROM email_history
            WHERE email_uid = %s
            ORDER BY received_at DESC
            LIMIT 1
        """
        
        cursor.execute(query, (uid,))
        email_data = cursor.fetchone()
        
        if not email_data:
            cursor.close()
            conn.close()
            return jsonify({'success': False, 'error': 'Email not found'}), 404
        
        # Pobierz historię emaili od tego nadawcy (kontekst)
        history_query = """
            SELECT subject, body_text, received_at
            FROM email_history
            WHERE sender_email = %s
            ORDER BY received_at DESC
            LIMIT 5
        """
        
        cursor.execute(history_query, (email_data['sender_email'],))
        history = cursor.fetchall()
        
        cursor.close()
        conn.close()
        
        # Przygotuj kontekst dla Claude
        body = email_data['body_text'] if email_data['body_text'] else email_data['body_html']
        
        history_context = ""
        if len(history) > 1:
            history_context = "\n\nHistoria poprzednich emaili od tego nadawcy:\n"
            for h in history[1:]:  # Pomijamy obecny email
                history_context += f"- {h['received_at'].strftime('%Y-%m-%d')}: {h['subject'][:100]}\n"
        
        # Prompt dla Claude
        client = Anthropic(api_key=config.CLAUDE_API_KEY)
        
        prompt = f"""Otrzymałem email od {email_data['sender_name']} ({email_data['sender_email']}).

Temat: {email_data['subject']}
Treść: {body[:2000]}
{history_context}

Zaproponuj 3 warianty odpowiedzi na tego emaila:

1. KRÓTKA I ZWIĘZŁA (2-3 zdania, konkretna)
2. FORMALNA I SZCZEGÓŁOWA (profesjonalna, pełna odpowiedź)
3. PRZYJAZNA I SWOBODNA (ciepła, nieformalna)

Zwróć odpowiedź w formacie JSON (bez markdown, bez ```json):
{{
  "short": "tekst krótkiej odpowiedzi",
  "formal": "tekst formalnej odpowiedzi",
  "friendly": "tekst przyjaznej odpowiedzi"
}}
"""

        message = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=1500,
            messages=[
                {"role": "user", "content": prompt}
            ]
        )
        
        response_text = message.content[0].text.strip()
        
        # Usuń markdown jeśli jest
        response_text = response_text.replace('```json', '').replace('```', '').strip()
        
        # Parsuj JSON
        suggestions = json.loads(response_text)
        
        return jsonify({
            'success': True,
            'suggestions': suggestions,
            'email': {
                'sender': email_data['sender_name'],
                'subject': email_data['subject']
            }
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: WYŚLIJ ODPOWIEDŹ
# =========================

@app.route('/api/emails/send', methods=['POST'])
def send_email_reply():
    """Wysyła odpowiedź na email przez SMTP"""
    try:
        data = request.json
        
        to_email = data.get('to')
        subject = data.get('subject')
        body = data.get('body')
        reply_to_uid = data.get('reply_to_uid')
        
        if not to_email or not subject or not body:
            return jsonify({'success': False, 'error': 'Missing required fields'}), 400
        
        # Utwórz wiadomość
        msg = MIMEMultipart('alternative')
        msg['From'] = config.SMTP_FROM
        msg['To'] = to_email
        msg['Subject'] = subject
        
        # Dodaj treść
        msg.attach(MIMEText(body, 'plain', 'utf-8'))
        
        # Wyślij przez SMTP
        server = smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT)
        server.starttls()
        server.login(config.SMTP_USER, config.SMTP_PASSWORD)
        server.send_message(msg)
        server.quit()
        
        print(f"Email wysłany do: {to_email}")
        
        return jsonify({
            'success': True,
            'message': 'Email wysłany pomyślnie'
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: AKCJE NA EMAILU
# =========================

@app.route('/api/emails/<uid>/action', methods=['POST'])
def email_action(uid):
    """Wykonuje akcję na emailu (pin, archive, delete, star)"""
    try:
        data = request.json
        action_type = data.get('action')  # pin, archive, delete, star
        
        if action_type not in ['pinned', 'archived', 'deleted', 'starred']:
            return jsonify({'success': False, 'error': 'Invalid action'}), 400
        
        conn = get_jarvis_db_connection()
        cursor = conn.cursor()
        
        # Usuń poprzednią akcję tego typu dla tego emaila
        delete_query = "DELETE FROM email_actions WHERE email_uid = %s AND action_type = %s"
        cursor.execute(delete_query, (uid, action_type))
        
        # Dodaj nową akcję
        insert_query = "INSERT INTO email_actions (email_uid, action_type) VALUES (%s, %s)"
        cursor.execute(insert_query, (uid, action_type))
        
        conn.commit()
        cursor.close()
        conn.close()
        
        # Jeśli delete - usuń też lokalny plik
        if action_type == 'deleted':
            output_dir = config.OUTPUT_DIR
            for filename in os.listdir(output_dir):
                if filename.endswith('.json'):
                    filepath = os.path.join(output_dir, filename)
                    try:
                        with open(filepath, 'r', encoding='utf-8') as f:
                            email_data = json.load(f)
                            if email_data.get('email_uid') == uid:
                                # Usuń JSON
                                os.remove(filepath)
                                # Usuń MP3
                                audio_file = email_data.get('audio_file')
                                if audio_file and os.path.exists(audio_file):
                                    os.remove(audio_file)
                                break
                    except:
                        continue
        
        return jsonify({
            'success': True,
            'message': f'Action {action_type} applied'
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: FILTRY
# =========================

@app.route('/api/emails/filters', methods=['GET'])
def get_email_filters():
    """Zwraca dostępne filtry (kategorie, nadawcy)"""
    try:
        conn = get_jarvis_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # Pobierz unikalne kategorie
        cursor.execute("SELECT DISTINCT category FROM email_history WHERE category IS NOT NULL")
        categories = [row['category'] for row in cursor.fetchall()]
        
        # Pobierz top nadawców
        cursor.execute("""
            SELECT sender_email, sender_name, COUNT(*) as count
            FROM email_history
            GROUP BY sender_email, sender_name
            ORDER BY count DESC
            LIMIT 20
        """)
        senders = cursor.fetchall()
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'categories': categories,
            'senders': senders
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: REGUŁY AUTOMATYZACJI
# =========================

@app.route('/api/emails/rules', methods=['GET'])
def get_email_rules():
    """Zwraca wszystkie reguły automatyzacji"""
    try:
        conn = get_jarvis_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT id, rule_name, condition_type, condition_value,
                   action_type, action_value, enabled, created_at
            FROM email_rules
            ORDER BY created_at DESC
        """
        
        cursor.execute(query)
        rules = cursor.fetchall()
        
        for rule in rules:
            if rule['created_at']:
                rule['created_at'] = rule['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'count': len(rules),
            'rules': rules
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/emails/rules', methods=['POST'])
def create_email_rule():
    """Tworzy nową regułę automatyzacji"""
    try:
        data = request.json
        
        rule_name = data.get('rule_name')
        condition_type = data.get('condition_type')  # sender, category, subject_contains, priority
        condition_value = data.get('condition_value')
        action_type = data.get('action_type')  # delete, archive, set_priority, notify
        action_value = data.get('action_value')
        
        if not all([rule_name, condition_type, condition_value, action_type]):
            return jsonify({'success': False, 'error': 'Missing required fields'}), 400
        
        conn = get_jarvis_db_connection()
        cursor = conn.cursor()
        
        query = """
            INSERT INTO email_rules
            (rule_name, condition_type, condition_value, action_type, action_value)
            VALUES (%s, %s, %s, %s, %s)
        """
        
        cursor.execute(query, (rule_name, condition_type, condition_value, action_type, action_value))
        
        conn.commit()
        rule_id = cursor.lastrowid
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'rule_id': rule_id,
            'message': 'Rule created successfully'
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# ENDPOINT: NBA PLAYER SUMMARIES (NOWE!)
# =========================

@app.route('/api/nba/players/favorites', methods=['GET'])
def get_favorite_players():
    """Zwraca listę ulubionych graczy z config"""
    try:
        # Lista ulubionych graczy (możesz to przenieść do config.py)
        favorite_player_ids = getattr(config, 'FAVORITE_NBA_PLAYERS', [
            201142,  # Kevin Durant
            201939,  # Stephen Curry
            2544,    # LeBron James
        ])
        
        conn = get_nba_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        placeholders = ','.join(['%s'] * len(favorite_player_ids))
        query = f"""
            SELECT player_id, first_name, last_name, team_id,
                   jersey_number, position, photo_url
            FROM players
            WHERE player_id IN ({placeholders})
        """
        
        cursor.execute(query, favorite_player_ids)
        players = cursor.fetchall()
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'count': len(players),
            'players': players
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/nba/players/<int:player_id>/summary', methods=['GET'])
def get_player_summary(player_id):
    """Generuje AI summary dla ostatniego meczu gracza"""
    try:
        days = request.args.get('days', 1, type=int)
        
        conn = get_nba_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # Pobierz dane gracza
        cursor.execute("""
            SELECT first_name, last_name, team_id, photo_url
            FROM players
            WHERE player_id = %s
        """, (player_id,))
        
        player = cursor.fetchone()
        if not player:
            cursor.close()
            conn.close()
            return jsonify({'success': False, 'error': 'Player not found'}), 404
        
        # Pobierz ostatnie statystyki
        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_score as home_team_score,
                g.away_score as away_team_score,
                g.game_status as 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.game_status = 'Final'
            ORDER BY g.game_date DESC
            LIMIT 1
        """
        
        cursor.execute(query, (player_id, date_from))
        stats = cursor.fetchone()
        
        if not stats:
            cursor.close()
            conn.close()
            return jsonify({
                'success': True,
                'has_game': False,
                'message': 'Gracz nie rozegrał meczu w tym okresie'
            })
        
        # Pobierz nazwy drużyn
        cursor.execute("""
            SELECT team_id, full_name, abbreviation, city, nickname
            FROM team_info
            WHERE team_id IN (%s, %s, %s)
        """, (player['team_id'], stats['home_team_id'], stats['away_team_id']))
        
        teams = {t['team_id']: t for t in cursor.fetchall()}
        
        cursor.close()
        conn.close()
        
        # Formatuj dane
        player_team = teams.get(player['team_id'])
        is_home = player['team_id'] == stats['home_team_id']
        opponent_id = stats['away_team_id'] if is_home else stats['home_team_id']
        opponent = teams.get(opponent_id)
        
        team_score = stats['home_team_score'] if is_home else stats['away_team_score']
        opp_score = stats['away_team_score'] if is_home else stats['home_team_score']
        result = "W" if team_score > opp_score else "L"
        
        # Oblicz procenty
        fg_pct = round(stats['field_goals_made'] / stats['field_goals_attempted'] * 100, 1) if stats['field_goals_attempted'] > 0 else 0
        three_pct = round(stats['three_pointers_made'] / stats['three_pointers_attempted'] * 100, 1) if stats['three_pointers_attempted'] > 0 else 0
        ft_pct = round(stats['free_throws_made'] / stats['free_throws_attempted'] * 100, 1) if stats['free_throws_attempted'] > 0 else 0
        
        game_data = {
            'player_name': f"{player['first_name']} {player['last_name']}",
            'team': player_team['full_name'] if player_team else 'Unknown',
            'team_abbr': player_team['abbreviation'] if player_team else 'UNK',
            'opponent': opponent['full_name'] if opponent else 'Unknown',
            'opponent_abbr': opponent['abbreviation'] if opponent else 'UNK',
            'result': result,
            'team_score': team_score,
            'opp_score': opp_score,
            'date': stats['game_date'].strftime('%Y-%m-%d') if stats['game_date'] else None,
            'minutes': stats['minutes_played'],
            'points': stats['points'],
            'rebounds': stats['rebounds'],
            'assists': stats['assists'],
            'steals': stats['steals'],
            'blocks': stats['blocks'],
            'turnovers': stats['turnovers'],
            'fg_made': stats['field_goals_made'],
            'fg_attempted': stats['field_goals_attempted'],
            'fg_pct': fg_pct,
            'three_made': stats['three_pointers_made'],
            'three_attempted': stats['three_pointers_attempted'],
            'three_pct': three_pct,
            'ft_made': stats['free_throws_made'],
            'ft_attempted': stats['free_throws_attempted'],
            'ft_pct': ft_pct,
            'plus_minus': stats['plus_minus']
        }
        
        # Generuj AI summary
        client = Anthropic(api_key=config.CLAUDE_API_KEY)
        
        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 = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=300,
            messages=[{"role": "user", "content": prompt}]
        )
        
        ai_summary = message.content[0].text.strip()
        
        return jsonify({
            'success': True,
            'has_game': True,
            'player': {
                'id': player_id,
                'name': game_data['player_name'],
                'photo_url': player['photo_url']
            },
            'game': {
                'date': game_data['date'],
                'team': game_data['team_abbr'],
                'opponent': game_data['opponent_abbr'],
                'result': result,
                'score': f"{game_data['team_score']}-{game_data['opp_score']}"
            },
            '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']}",
                'three_pct': game_data['three_pct'],
                'plus_minus': game_data['plus_minus']
            },
            'ai_summary': ai_summary
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/nba/players/summaries', methods=['GET'])
def get_all_player_summaries():
    """Generuje AI summaries dla wszystkich ulubionych graczy"""
    try:
        days = request.args.get('days', 1, type=int)
        
        favorite_player_ids = getattr(config, 'FAVORITE_NBA_PLAYERS', [
            201142,  # Kevin Durant
            201939,  # Stephen Curry
            2544,    # LeBron James
        ])
        
        summaries = []
        
        for player_id in favorite_player_ids:
            # Wywołaj funkcję dla pojedynczego gracza
            result = get_player_summary(player_id)
            data = result[0].get_json()
            
            if data.get('success') and data.get('has_game'):
                summaries.append(data)
        
        return jsonify({
            'success': True,
            'count': len(summaries),
            'summaries': summaries
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# =========================
# POZOSTAŁE ENDPOINTY (Pogoda, NBA, Użytkownicy, Stats)
# =========================

@app.route('/api/weather', methods=['GET'])
def get_weather():
    """Pobiera pogodę z OpenWeatherMap"""
    try:
        url = f"https://api.openweathermap.org/data/2.5/weather?lat={config.WEATHER_LAT}&lon={config.WEATHER_LON}&appid={config.OPENWEATHER_API_KEY}&units=metric&lang=pl"
        response = requests.get(url, timeout=10)
        current = response.json()
        
        forecast_url = f"https://api.openweathermap.org/data/2.5/forecast?lat={config.WEATHER_LAT}&lon={config.WEATHER_LON}&appid={config.OPENWEATHER_API_KEY}&units=metric&lang=pl"
        forecast_response = requests.get(forecast_url, timeout=10)
        forecast = forecast_response.json()
        
        weather_data = {
            'current': {
                'temp': round(current['main']['temp'], 1),
                'feels_like': round(current['main']['feels_like'], 1),
                'humidity': current['main']['humidity'],
                'pressure': current['main']['pressure'],
                'description': current['weather'][0]['description'],
                'icon': current['weather'][0]['icon'],
                'wind_speed': round(current['wind']['speed'], 1),
                'clouds': current['clouds']['all']
            },
            'tonight': None,
            'city': config.WEATHER_CITY
        }
        
        now = datetime.now()
        for item in forecast['list'][:8]:
            forecast_time = datetime.fromtimestamp(item['dt'])
            if forecast_time.hour >= 21 or forecast_time.hour <= 3:
                weather_data['tonight'] = {
                    'temp': round(item['main']['temp'], 1),
                    'clouds': item['clouds']['all'],
                    'humidity': item['main']['humidity'],
                    'description': item['weather'][0]['description'],
                    'time': forecast_time.strftime('%H:%M')
                }
                break
        
        clouds = weather_data['current']['clouds']
        if clouds < 20:
            astro_quality = "Doskonałe"
        elif clouds < 40:
            astro_quality = "Dobre"
        elif clouds < 70:
            astro_quality = "Średnie"
        else:
            astro_quality = "Słabe"
        
        weather_data['astro_quality'] = astro_quality
        
        return jsonify({
            'success': True,
            'weather': weather_data
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/users/recent', methods=['GET'])
def get_recent_users():
    """Zwraca nowych użytkowników (niepotwierdzonych)"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT id, name, city, model, experience,
                   latitude, longitude, created_at, status
            FROM users
            WHERE status = 'pending'
            ORDER BY created_at DESC
            LIMIT 5"""
        
        cursor.execute(query)
        users = cursor.fetchall()
        
        for user in users:
            user['created_at'] = user['created_at'].strftime('%Y-%m-%d %H:%M')
            if user['latitude']:
                user['latitude'] = float(user['latitude'])
            if user['longitude']:
                user['longitude'] = float(user['longitude'])
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'count': len(users),
            'users': users
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/astrophoto/pending', methods=['GET'])
def get_pending_astrophoto_locations():
    """Zwraca astromiejscówki oczekujące na zatwierdzenie"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        query = """
            SELECT id, name, description, latitude, longitude,
                   bortle_class, access_type, walk_distance,
                   parking_info, added_by, best_targets,
                   obstacles, notes, created_at
            FROM astrophoto_locations
            WHERE status = 'pending'
            ORDER BY created_at DESC
            LIMIT 20
        """
        
        cursor.execute(query)
        locations = cursor.fetchall()
        
        for loc in locations:
            loc['created_at'] = loc['created_at'].strftime('%Y-%m-%d %H:%M')
            if loc['latitude']:
                loc['latitude'] = float(loc['latitude'])
            if loc['longitude']:
                loc['longitude'] = float(loc['longitude'])
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'count': len(locations),
            'locations': locations
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/nba/games/recent', methods=['GET'])
def get_nba_games_recent():
    """Zwraca ostatnie mecze NBA (3 dni wstecz)"""
    try:
        conn = get_nba_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        days_back = 3
        start_date = (datetime.now() - timedelta(days=days_back)).date()
        
        query = """
            SELECT
                g.game_id,
                g.game_date,
                g.game_time,
                g.home_team_id,
                g.away_team_id,
                g.home_score,
                g.away_score,
                g.game_status,
                g.period,
                ht.abbreviation as home_abbr,
                ht.nickname as home_name,
                ht.city as home_city,
                at.abbreviation as away_abbr,
                at.nickname as away_name,
                at.city as away_city
            FROM games g
            JOIN team_info ht ON g.home_team_id = ht.team_id
            JOIN team_info at ON g.away_team_id = at.team_id
            WHERE g.game_date >= %s
            ORDER BY g.game_date DESC, g.game_time DESC
            LIMIT 10
        """
        
        cursor.execute(query, (start_date,))
        games = cursor.fetchall()
        
        for game in games:
            game['home_logo'] = f"https://cdn.nba.com/logos/nba/{game['home_team_id']}/primary/L/logo.svg"
            game['away_logo'] = f"https://cdn.nba.com/logos/nba/{game['away_team_id']}/primary/L/logo.svg"
            game['home_full_name'] = f"{game['home_city']} {game['home_name']}"
            game['away_full_name'] = f"{game['away_city']} {game['away_name']}"
            
            if game['game_time']:
                game['game_time'] = str(game['game_time'])
            if game['game_date']:
                game['game_date'] = game['game_date'].strftime('%Y-%m-%d')
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'count': len(games),
            'games': games
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/stats', methods=['GET'])
def get_dashboard_stats():
    """Zwraca statystyki dla dashboardu"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        cursor.execute("SELECT COUNT(*) as total FROM users WHERE status='approved'")
        total_users = cursor.fetchone()['total']
        
        yesterday = datetime.now() - timedelta(days=1)
        cursor.execute("SELECT COUNT(*) as new_users FROM users WHERE created_at >= %s", (yesterday,))
        new_users_24h = cursor.fetchone()['new_users']
        
        week_ago = datetime.now() - timedelta(days=7)
        cursor.execute("SELECT COUNT(*) as new_users FROM users WHERE created_at >= %s", (week_ago,))
        new_users_7d = cursor.fetchone()['new_users']
        
        cursor.execute("SELECT COUNT(*) as pending FROM astrophoto_locations WHERE status='pending'")
        pending_locations = cursor.fetchone()['pending']
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'success': True,
            'stats': {
                'total_users': total_users,
                'new_users_24h': new_users_24h,
                'new_users_7d': new_users_7d,
                'pending_locations': pending_locations
            }
        })
    
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """Sprawdza czy API działa"""
    return jsonify({
        'success': True,
        'message': 'API is running',
        'timestamp': datetime.now().isoformat()
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)