from flask import Blueprint, render_template, request, jsonify
from web.services.stats_service import StatsService
import time

bp = Blueprint('main', __name__)

@bp.route('/')
def index():
    recent_matches = StatsService.get_recent_matches(limit=5)
    daily_counts = StatsService.get_daily_match_counts()
    live_matches = StatsService.get_live_matches()
    
    # Convert rows to dict for easier JS usage
    heatmap_data = {}
    if daily_counts:
        for row in daily_counts:
            heatmap_data[row['day']] = row['count']
            
    return render_template('home/index.html', recent_matches=recent_matches, heatmap_data=heatmap_data, live_matches=live_matches)

from web.services.etl_service import EtlService

@bp.route('/parse_match', methods=['POST'])
def parse_match():
    url = request.form.get('url')
    if not url or '5eplay.com' not in url:
        return jsonify({'success': False, 'message': 'Invalid 5EPlay URL'})
    
    # Trigger L1A.py with URL argument
    success, msg = EtlService.run_script('L1A.py', args=[url])
    
    if success:
        return jsonify({'success': True, 'message': 'Match parsing completed successfully!'})
    else:
        return jsonify({'success': False, 'message': f'Error: {msg}'})
