"""Dashboard principal."""
from __future__ import annotations

from flask import Blueprint, render_template

from .. import audit, services
from ..auth import login_required
from ..config import get_config
from ..db import get_db

bp = Blueprint("dashboard", __name__)


@bp.get("/")
@login_required
def index():
    from .. import anablock, federacao

    db = get_db()
    total_active = db.execute(
        "SELECT COUNT(*) AS c FROM blocked_domains WHERE active = 1"
    ).fetchone()["c"]
    total_processes = db.execute(
        "SELECT COUNT(DISTINCT process_no) AS c FROM blocked_domains WHERE active = 1"
    ).fetchone()["c"]
    total_allowed = db.execute(
        "SELECT COUNT(*) AS c FROM liberacoes WHERE active = 1"
    ).fetchone()["c"]
    last_block = db.execute(
        "SELECT domain, created_at FROM blocked_domains ORDER BY id DESC LIMIT 1"
    ).fetchone()

    from ..db import get_provider

    provider = get_provider()

    return render_template(
        "dashboard.html",
        services=services.overview(),
        total_active=total_active,
        total_processes=total_processes,
        total_allowed=total_allowed,
        last_block=dict(last_block) if last_block else None,
        recent_logs=audit.recent(10),
        cfg=get_config(),
        anablock=anablock.get_settings(),
        federacao=federacao.get_publicacao(),
        federacao_peers=len(federacao.listar_peers()),
        provider_incompleto=not (provider.get("trade_name") or "").strip(),
    )

