from flask import Blueprint, render_template
from flask_login import login_required
from app.models import Penduduk, ClusteringSession, User
from app import db
from sqlalchemy import func

dashboard_bp = Blueprint('dashboard', __name__)


@dashboard_bp.route('/dashboard')
@login_required
def index():
    total_penduduk = Penduduk.query.count()
    total_sesi = ClusteringSession.query.count()
    total_user = User.query.count()

    # Sesi terbaru
    sesi_terbaru = ClusteringSession.query.order_by(
        ClusteringSession.created_at.desc()
    ).limit(5).all()

    # Data per tahap
    tahap_counts = db.session.query(
        Penduduk.tahap, func.count(Penduduk.id)
    ).group_by(Penduduk.tahap).all()

    # Distribusi clustering
    cluster_dist = db.session.query(
        ClusteringSession.metode, func.count(ClusteringSession.id)
    ).group_by(ClusteringSession.metode).all()

    return render_template('dashboard/index.html',
        total_penduduk=total_penduduk,
        total_sesi=total_sesi,
        total_user=total_user,
        sesi_terbaru=sesi_terbaru,
        tahap_counts=tahap_counts,
        cluster_dist=cluster_dist,
    )
