from __future__ import annotations

import html

from .processes import PROCESS_STATUS_LABELS


ENVIRONMENT_LABELS = {
    "producao": "Produção",
    "producao_restrita": "Produção restrita",
}


def _esc(value: object) -> str:
    return html.escape(str(value or ""), quote=True)


def render_processes_page(rows: list[dict[str, str]]) -> str:
    table_rows = ""
    for item in rows:
        raw_status = item["status"]
        status_label = PROCESS_STATUS_LABELS.get(raw_status, raw_status)
        environment = ENVIRONMENT_LABELS.get(item["ambiente"], item["ambiente"])
        error_title = item.get("last_error_message") or "Abrir detalhes do processo"
        table_rows += f"""
        <tr>
          <td data-sort-value="{_esc(item['id'])}">#{_esc(item['id'])}</td>
          <td>{_esc(item['municipio_nome'])}</td>
          <td>{_esc(item['codigo_siafi'])}</td>
          <td>{_esc(environment)}</td>
          <td>{_esc(item['perfil'])}</td>
          <td><span class="status status-{_esc(raw_status)}">{_esc(status_label)}</span></td>
          <td data-sort-value="{_esc(item['attempts'])}">{_esc(item['attempts'])}</td>
          <td>{_esc(item['updated_at'])}</td>
          <td>{_esc(item['finished_at']) or '-'}</td>
          <td>
            <button class="icon-button secondary" type="button" data-process-id="{_esc(item['id'])}" title="{_esc(error_title)}" aria-label="Ver detalhes do processo #{_esc(item['id'])}">
              <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z"></path><circle cx="12" cy="12" r="3"></circle></svg>
            </button>
          </td>
        </tr>"""
    if not table_rows:
        table_rows = '<tr data-empty><td colspan="10">Nenhum processo registrado.</td></tr>'
    return f"""
    <div class="title-row">
      <div><h1>Acompanhar processos</h1><p class="hint">Sincronizações encaminhadas para a fila persistente.</p></div>
    </div>
    <fieldset class="panel-fieldset">
      <legend>Processos de sincronização</legend>
      <table class="data-table process-table" data-page-size="25">
        <thead><tr><th>ID</th><th>Município</th><th>SIAFI</th><th>Ambiente</th><th>Perfil</th><th>Status</th><th>Tentativas</th><th>Atualizado</th><th>Finalizado</th><th data-no-sort>Detalhes</th></tr></thead>
        <tbody>{table_rows}</tbody>
      </table>
    </fieldset>
    <dialog id="process-detail-dialog" class="process-dialog">
      <div class="dialog-header">
        <h2>Detalhes do processo</h2>
        <button type="button" class="dialog-close secondary" data-dialog-close aria-label="Fechar">&times;</button>
      </div>
      <p class="hint" data-process-loading>Carregando detalhes...</p>
      <dl class="process-details" data-process-details></dl>
      <section class="process-error" data-process-error hidden>
        <h3>Mensagem de erro</h3>
        <pre data-process-error-text></pre>
      </section>
      <h3>Logs recentes do município</h3>
      <div class="table-scroll">
        <table class="logs-table">
          <thead><tr><th>Data</th><th>Nível</th><th>Evento</th><th>Mensagem</th><th>Contexto</th></tr></thead>
          <tbody data-process-logs></tbody>
        </table>
      </div>
    </dialog>
    """
