from __future__ import annotations

from flask import Blueprint, render_template, request
from flask_login import login_required

from ..services.dates import local_now, month_label
from ..services.monthly import archive_months_missing_up_to_previous, compute_monthly_scores, get_archived_months, get_snapshot_rows


bp = Blueprint("scoreboard", __name__, url_prefix="/scoreboard")


@bp.route("")
@login_required
def index():
    archive_months_missing_up_to_previous()
    now = local_now()
    current_rows = compute_monthly_scores(now.year, now.month)
    archive_options = get_archived_months(limit=18)

    selected = request.args.get("archive")
    selected_archive = selected
    selected_year = selected_month = None
    archived_rows = []
    if selected:
        year_str, month_str = selected.split("-")
        selected_year, selected_month = int(year_str), int(month_str)
        archived_rows = get_snapshot_rows(selected_year, selected_month)
    elif archive_options:
        selected_year, selected_month = archive_options[0]
        selected_archive = f"{selected_year}-{selected_month:02d}"
        archived_rows = get_snapshot_rows(selected_year, selected_month)

    return render_template(
        "scoreboard/index.html",
        current_rows=current_rows,
        current_label=month_label(now.year, now.month),
        archive_options=archive_options,
        selected_archive=selected_archive,
        archived_rows=archived_rows,
        archive_label=month_label(selected_year, selected_month) if selected_year and selected_month else None,
        max_points=max([row["total_points"] for row in current_rows], default=1),
    )
