from flask import Blueprint, render_template, request, jsonify
from web.services.opponent_service import OpponentService
from web.config import Config

bp = Blueprint('opponents', __name__, url_prefix='/opponents')

@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort', 'matches')
    search = request.args.get('search')
    
    opponents, total = OpponentService.get_opponent_list(page, Config.ITEMS_PER_PAGE, sort_by, search)
    total_pages = (total + Config.ITEMS_PER_PAGE - 1) // Config.ITEMS_PER_PAGE
    
    # Global stats for dashboard
    stats_summary = OpponentService.get_global_opponent_stats()
    map_stats = OpponentService.get_map_opponent_stats()
    
    return render_template('opponents/index.html', 
                         opponents=opponents, 
                         total=total, 
                         page=page, 
                         total_pages=total_pages, 
                         sort_by=sort_by,
                         stats_summary=stats_summary,
                         map_stats=map_stats)

@bp.route('/<steam_id>')
def detail(steam_id):
    data = OpponentService.get_opponent_detail(steam_id)
    if not data:
        return "Opponent not found", 404
        
    return render_template('opponents/detail.html', **data)
