"""Logs de sistema e auditoria."""
from __future__ import annotations

import csv
import io
from datetime import datetime

from flask import Blueprint, Response, render_template, request

from .. import audit
from ..auth import login_required

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

PER_PAGE = 50
EXPORT_LIMIT = 100000


@bp.get("/")
@login_required
def index():
    username = (request.args.get("username") or "").strip()
    action = (request.args.get("action") or "").strip()
    date_from = (request.args.get("date_from") or "").strip()
    date_to = (request.args.get("date_to") or "").strip()
    page = max(int(request.args.get("page", 1) or 1), 1)

    rows, total = audit.search(username, action, date_from, date_to, page, PER_PAGE)
    pages = max((total + PER_PAGE - 1) // PER_PAGE, 1)
    return render_template(
        "logs.html",
        rows=rows,
        total=total,
        page=page,
        pages=pages,
        username=username,
        action=action,
        date_from=date_from,
        date_to=date_to,
    )


@bp.get("/exportar.csv")
@login_required
def export_csv():
    """Exportacao manual dos registros de auditoria (respeita os filtros da tela)."""
    username = (request.args.get("username") or "").strip()
    action = (request.args.get("action") or "").strip()
    date_from = (request.args.get("date_from") or "").strip()
    date_to = (request.args.get("date_to") or "").strip()

    rows, total = audit.search(username, action, date_from, date_to, 1, EXPORT_LIMIT)

    buffer = io.StringIO()
    writer = csv.writer(buffer, delimiter=";")
    writer.writerow(["ID", "Data/Hora (UTC)", "Usuario", "Acao", "Detalhe", "IP"])
    for row in rows:
        writer.writerow(
            [
                row["id"],
                row["created_at"],
                row["username"],
                row["action"],
                (row["detail"] or "").replace("\n", " "),
                row["ip_address"],
            ]
        )

    audit.log("exportacao_auditoria", f"{len(rows)} de {total} registro(s) exportados")
    filename = f"auditoria-{datetime.now().strftime('%Y%m%d-%H%M%S')}.csv"
    return Response(
        "\ufeff" + buffer.getvalue(),
        mimetype="text/csv; charset=utf-8",
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )
