"""Operational queue diagnostic routes.

Moved from app.admin_dashboard in v4.7.2. The handlers still reuse
legacy helpers to keep this refactor behavior-preserving.
"""
from fastapi import APIRouter
import app.admin_dashboard as legacy
from app.admin_dashboard import *  # noqa: F401,F403

router = APIRouter()


@router.get("/queues", response_class=HTMLResponse)
@router.get("/filas", response_class=HTMLResponse)
async def queues_page():
    metrics = get_admin_dashboard_metrics()
    queue_defs = [
        ("vendas", "Comercial", "Orçamentos, propostas e oportunidades", "pending_vendas", "cf-chip-blue"),
        ("financeiro", "Financeiro", "Pagamentos, faturas e comprovativos", "pending_financeiro", "cf-chip-green"),
        ("operacoes", "Logística", "Envios, recolhas e entregas", "pending_operacoes", "cf-chip-orange"),
        ("suporte", "Suporte", "Técnico, garantia e pós-venda", "pending_suporte", "cf-chip-purple"),
        ("rever", "Rever", "Casos ambíguos ou baixa confiança", "pending_rever", "cf-chip-gray"),
    ]

    rows = ""
    chart_items = ""
    for route_key, label, description, metric_key, chip_class in queue_defs:
        count = int(metrics.get(metric_key) or 0)
        active_tasks = []
        try:
            active_tasks = list_tasks(status="pending", route=route_key, limit=1)
        except Exception:
            active_tasks = []
        priority = "Alta" if route_key in {"financeiro", "operacoes"} and count else ("Média" if count else "Baixa")
        rows += f'''
        <tr>
          <td><span class="cf-chip {chip_class}">{esc(label)}</span></td>
          <td>{esc(description)}</td>
          <td><strong>{count}</strong></td>
          <td><span class="cf-chip {'cf-chip-red' if priority == 'Alta' else 'cf-chip-orange' if priority == 'Média' else 'cf-chip-gray'}">{esc(priority)}</span></td>
          <td>
            <a class="btn btn-outline-primary btn-sm" href="/tasks?status=pending&route={esc(route_key)}">Abrir</a>
          </td>
        </tr>
        '''
        chart_items += f'''
        <div class="mb-2">
          <div class="d-flex justify-content-between"><span>{esc(label)}</span><strong>{count}</strong></div>
          <div class="progress" style="height:.55rem"><div class="progress-bar" style="width:{min(100, count * 4)}%"></div></div>
        </div>
        '''

    body = f'''
    <div class="row g-3">
      <div class="col-xl-8">
        <section class="card cf-card">
          <div class="card-body p-0">
            <div class="p-3 border-bottom">
              <h2 class="cf-section-title">Filas</h2>
              <div class="small text-secondary">Gestão de distribuição de tarefas por equipa.</div>
            </div>
            <div class="cf-table-wrap border-0 rounded-0">
              <table class="table cf-table">
                <thead><tr><th>Fila</th><th>Descrição</th><th>Tarefas</th><th>Prioridade</th><th>Ações</th></tr></thead>
                <tbody>{rows}</tbody>
              </table>
            </div>
          </div>
        </section>
      </div>
      <div class="col-xl-4">
        <section class="card cf-card">
          <div class="card-body p-4">
            <h2 class="cf-section-title mb-3">Distribuição de tarefas</h2>
            {chart_items}
          </div>
        </section>
      </div>
    </div>
    '''
    return layout("Filas", "Gestão de filas e distribuição de tarefas", body, "queues")


