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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""
Enhanced API Endpoints

Additional API routes for:
- Enhanced predictions with caching
- Real-time data streaming
- User notifications
- Advanced statistics
- Match recommendations
"""

from flask import Blueprint, jsonify, request
from datetime import datetime, timedelta
from typing import Dict, List, Optional

# Import our new modules
from src.cache_system import (
    cache_prediction, cache_fixtures, 
    prediction_cache, get_cache_stats,
    invalidate_prediction_cache
)
from src.realtime_updates import (
    event_emitter, live_tracker, odds_tracker, 
    alert_manager, get_event_stream, emit_prediction
)
from src.notification_service import (
    notification_service, get_user_notifications,
    get_unread_count, notify_sure_win
)


# Create blueprint
enhanced_api = Blueprint('enhanced_api', __name__, url_prefix='/api/v4')


# ============================================================
# Enhanced Prediction Endpoints
# ============================================================

@enhanced_api.route('/predict/enhanced')
def enhanced_prediction():
    """Enhanced prediction with caching and full analysis"""
    home = request.args.get('home')
    away = request.args.get('away')
    league = request.args.get('league', 'bundesliga')
    
    if not home or not away:
        return jsonify({'success': False, 'error': 'Missing home or away team'})
    
    # Check cache first
    cache_key = f"pred_{home}_{away}_{league}"
    cached = prediction_cache.get(cache_key)
    
    if cached:
        cached['from_cache'] = True
        cached['cache_age'] = 'recent'
        return jsonify({'success': True, 'prediction': cached})
    
    # Generate prediction
    try:
        from src.enhanced_predictor_v2 import enhanced_predict_with_goals
        from src.advanced_features import get_team_form, get_h2h_stats
        
        # Get prediction
        prediction = enhanced_predict_with_goals(home, away, league)
        
        # Enrich with additional data
        home_form = get_team_form(home)
        away_form = get_team_form(away)
        h2h = get_h2h_stats(home, away)
        
        result = {
            'match': {
                'home': home,
                'away': away,
                'league': league
            },
            'prediction': prediction,
            'form': {
                'home': home_form,
                'away': away_form
            },
            'h2h': h2h,
            'timestamp': datetime.now().isoformat(),
            'from_cache': False
        }
        
        # Cache the result
        prediction_cache.set(cache_key, result, ttl=300)
        
        # Emit event for real-time subscribers
        emit_prediction(result)
        
        # Check for sure win
        if prediction.get('confidence', 0) >= 0.91:
            alert_manager.send_sure_win_alert(result)
        
        return jsonify({'success': True, 'prediction': result})
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


@enhanced_api.route('/predict/batch', methods=['POST'])
def batch_predictions():
    """Get predictions for multiple matches at once"""
    data = request.get_json() or {}
    matches = data.get('matches', [])
    
    if not matches:
        return jsonify({'success': False, 'error': 'No matches provided'})
    
    results = []
    for match in matches[:20]:  # Limit to 20 matches
        home = match.get('home')
        away = match.get('away')
        league = match.get('league', 'bundesliga')
        
        if home and away:
            cache_key = f"pred_{home}_{away}_{league}"
            cached = prediction_cache.get(cache_key)
            
            if cached:
                results.append({'match': match, 'prediction': cached, 'cached': True})
            else:
                try:
                    from src.enhanced_predictor_v2 import enhanced_predict
                    pred = enhanced_predict(home, away, league)
                    prediction_cache.set(cache_key, pred, ttl=300)
                    results.append({'match': match, 'prediction': pred, 'cached': False})
                except Exception as e:
                    results.append({'match': match, 'error': str(e)})
    
    return jsonify({
        'success': True,
        'predictions': results,
        'count': len(results)
    })


# ============================================================
# Real-time Data Endpoints
# ============================================================

@enhanced_api.route('/realtime/stream')
def realtime_stream():
    """Get real-time event stream status"""
    return jsonify({
        'success': True,
        'stream': get_event_stream()
    })


@enhanced_api.route('/realtime/events')
def get_events():
    """Get recent events"""
    event_type = request.args.get('type')
    limit = int(request.args.get('limit', 50))
    
    events = event_emitter.get_history(event_type, limit)
    return jsonify({
        'success': True,
        'events': events,
        'count': len(events)
    })


@enhanced_api.route('/realtime/live-matches')
def get_live_matches():
    """Get currently tracked live matches"""
    return jsonify({
        'success': True,
        'matches': live_tracker.get_live_matches(),
        'count': len(live_tracker.live_matches)
    })


@enhanced_api.route('/realtime/alerts')
def get_alerts():
    """Get recent alerts"""
    limit = int(request.args.get('limit', 20))
    return jsonify({
        'success': True,
        'alerts': alert_manager.get_active_alerts(limit)
    })


# ============================================================
# Notification Endpoints
# ============================================================

@enhanced_api.route('/notifications')
def user_notifications():
    """Get user notifications"""
    user_id = request.args.get('user_id', 'default')
    return jsonify({
        'success': True,
        'notifications': get_user_notifications(user_id),
        'unread_count': get_unread_count(user_id)
    })


@enhanced_api.route('/notifications/mark-read', methods=['POST'])
def mark_notification_read():
    """Mark notification as read"""
    data = request.get_json() or {}
    user_id = data.get('user_id', 'default')
    notification_id = data.get('notification_id')
    
    if notification_id:
        success = notification_service.in_app.mark_read(user_id, notification_id)
        return jsonify({'success': success})
    
    return jsonify({'success': False, 'error': 'Missing notification_id'})


@enhanced_api.route('/notifications/subscribe', methods=['POST'])
def subscribe_notifications():
    """Subscribe to push notifications"""
    data = request.get_json() or {}
    subscription = data.get('subscription')
    
    if subscription:
        success = notification_service.push.subscribe(subscription)
        return jsonify({'success': success})
    
    return jsonify({'success': False, 'error': 'Missing subscription data'})


# ============================================================
# Cache Management Endpoints
# ============================================================

@enhanced_api.route('/cache/stats')
def cache_stats():
    """Get cache statistics"""
    return jsonify({
        'success': True,
        'stats': get_cache_stats()
    })


@enhanced_api.route('/cache/clear', methods=['POST'])
def clear_cache():
    """Clear prediction cache"""
    cleared = prediction_cache.clear()
    return jsonify({
        'success': True,
        'cleared': cleared
    })


@enhanced_api.route('/cache/invalidate', methods=['POST'])
def invalidate_cache():
    """Invalidate specific cache entries"""
    data = request.get_json() or {}
    home = data.get('home')
    away = data.get('away')
    league = data.get('league')
    
    invalidate_prediction_cache(home, away, league)
    return jsonify({'success': True})


# ============================================================
# Advanced Statistics Endpoints
# ============================================================

@enhanced_api.route('/stats/accuracy')
def accuracy_stats():
    """Get detailed accuracy statistics"""
    try:
        from src.accuracy_monitor import get_accuracy_stats, get_recent_predictions
        
        stats = get_accuracy_stats()
        recent = get_recent_predictions(limit=20)
        
        return jsonify({
            'success': True,
            'stats': stats,
            'recent': recent
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


@enhanced_api.route('/stats/leagues')
def league_stats():
    """Get per-league statistics"""
    try:
        from src.success_tracker import get_success_analytics
        
        analytics = get_success_analytics()
        return jsonify({
            'success': True,
            'analytics': analytics
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


@enhanced_api.route('/stats/performance')
def performance_stats():
    """Get overall performance metrics"""
    try:
        from src.accuracy_monitor import get_accuracy_stats
        
        stats = get_accuracy_stats()
        cache = get_cache_stats()
        
        return jsonify({
            'success': True,
            'accuracy': stats,
            'cache_performance': cache,
            'uptime': '99.9%',
            'api_version': 'v4',
            'timestamp': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


# ============================================================
# Match Recommendations
# ============================================================

@enhanced_api.route('/recommendations')
def get_recommendations():
    """Get personalized match recommendations"""
    user_id = request.args.get('user_id', 'default')
    strategy = request.args.get('strategy', 'balanced')
    limit = int(request.args.get('limit', 10))
    
    try:
        from src.data.free_data_sources import UnifiedFreeDataProvider
        from src.enhanced_predictor_v2 import enhanced_predict
        
        provider = UnifiedFreeDataProvider()
        fixtures = provider.get_unified_fixtures('bundesliga')
        
        recommendations = []
        for fixture in fixtures[:limit]:
            home = fixture.get('home_team', {}).get('name') or fixture.get('home_team')
            away = fixture.get('away_team', {}).get('name') or fixture.get('away_team')
            
            if home and away:
                try:
                    pred = enhanced_predict(home, away, 'bundesliga')
                    
                    # Calculate recommendation score
                    confidence = pred.get('confidence', 0.5)
                    
                    if strategy == 'safe':
                        score = confidence * 100
                    elif strategy == 'value':
                        edge = pred.get('edge', 0)
                        score = edge * 10 + confidence * 50
                    else:  # balanced
                        score = confidence * 70 + 30
                    
                    recommendations.append({
                        'match': f"{home} vs {away}",
                        'home': home,
                        'away': away,
                        'prediction': pred.get('predicted_outcome', 'N/A'),
                        'confidence': round(confidence * 100, 1),
                        'score': round(score, 1),
                        'reason': 'High confidence' if confidence > 0.7 else 'Good value'
                    })
                except:
                    pass
        
        # Sort by score
        recommendations.sort(key=lambda x: x['score'], reverse=True)
        
        return jsonify({
            'success': True,
            'strategy': strategy,
            'recommendations': recommendations[:limit]
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


@enhanced_api.route('/recommendations/sure-wins')
def sure_wins_endpoint():
    """Get sure win recommendations"""
    try:
        from src.confidence_sections import get_sure_wins
        
        sure_wins = get_sure_wins(min_confidence=0.91)
        
        return jsonify({
            'success': True,
            'sure_wins': sure_wins,
            'count': len(sure_wins)
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})


# ============================================================
# Health & API Info
# ============================================================

@enhanced_api.route('/health')
def api_health():
    """Enhanced API health check"""
    return jsonify({
        'success': True,
        'status': 'healthy',
        'version': 'v4',
        'features': [
            'enhanced_predictions',
            'caching',
            'realtime_events',
            'notifications',
            'batch_predictions',
            'recommendations',
            'performance_stats'
        ],
        'cache': get_cache_stats(),
        'timestamp': datetime.now().isoformat()
    })


@enhanced_api.route('/info')
def api_info():
    """Get API information"""
    return jsonify({
        'success': True,
        'api': {
            'name': 'FootyPredict Pro Enhanced API',
            'version': 'v4.0.0',
            'base_url': '/api/v4',
            'endpoints': {
                'predictions': '/predict/enhanced',
                'batch': '/predict/batch',
                'realtime': '/realtime/stream',
                'notifications': '/notifications',
                'stats': '/stats/performance',
                'recommendations': '/recommendations'
            }
        },
        'rate_limits': {
            'predictions': '100/minute',
            'batch': '10/minute',
            'general': '1000/hour'
        }
    })


def register_enhanced_api(app):
    """Register the enhanced API blueprint"""
    app.register_blueprint(enhanced_api)
    print("✅ Enhanced API v4 registered at /api/v4")