"""Progress bars com Rich."""

from __future__ import annotations

import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from rich.progress import Progress, TaskID


class OcrProgress:
    """Gerencia progress bars para render e OCR."""

    def __init__(self, verbose: bool = False):
        from rich.progress import BarColumn, Progress, TextColumn, TimeRemainingColumn

        self.verbose = verbose
        self.progress = Progress(
            TextColumn("[bold blue]{task.description}"),
            BarColumn(),
            TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
            TextColumn("({task.completed}/{task.total})"),
            TimeRemainingColumn(),
        )
        self._render_task: TaskID | None = None
        self._ocr_task: TaskID | None = None
        self._start_time: float = 0

    def __enter__(self):
        self.progress.__enter__()
        self._start_time = time.perf_counter()
        return self

    def __exit__(self, *args):
        self.progress.__exit__(*args)

    def add_render_task(self, total: int) -> None:
        self._render_task = self.progress.add_task("Render PDF", total=total)

    def add_ocr_task(self, total: int) -> None:
        self._ocr_task = self.progress.add_task("OCR", total=total)

    def update_render(self, done: int, total: int) -> None:
        if self._render_task is not None:
            self.progress.update(self._render_task, completed=done)

    def update_ocr(self, done: int, total: int) -> None:
        if self._ocr_task is not None:
            self.progress.update(self._ocr_task, completed=done)

    @property
    def elapsed(self) -> float:
        return time.perf_counter() - self._start_time


def print_summary(
    total_pdfs: int,
    total_pages: int,
    total_texts: int,
    elapsed: float,
) -> None:
    """Imprime resumo final da execução."""
    from rich.console import Console
    from rich.table import Table

    console = Console()
    table = Table(title="Resumo", show_header=False, border_style="blue")
    table.add_column("Métrica", style="bold")
    table.add_column("Valor", justify="right")

    table.add_row("PDFs processados", str(total_pdfs))
    table.add_row("Total de páginas", str(total_pages))
    table.add_row("Textos extraídos", str(total_texts))
    table.add_row("Tempo total", f"{elapsed:.1f}s ({elapsed / 60:.1f}min)")
    if total_pages > 0:
        table.add_row("Média por página", f"{elapsed / total_pages * 1000:.0f}ms")

    console.print()
    console.print(table)
