"""CLI principal do tecjustica-ocr."""

from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer
from rich.console import Console

from . import __version__

app = typer.Typer(
    name="tecjustica-ocr",
    help="Extração OCR de processos judiciais — PDF para Markdown.",
    add_completion=False,
    invoke_without_command=True,
)
console = Console()


def version_callback(value: bool):
    if value:
        console.print(f"tecjustica-ocr {__version__}")
        raise typer.Exit()


@app.callback()
def callback(
    version: Optional[bool] = typer.Option(
        None,
        "--version",
        "-V",
        callback=version_callback,
        is_eager=True,
        help="Mostra a versão.",
    ),
):
    """Extração OCR de processos judiciais — PDF para Markdown."""


@app.command()
def run(
    caminho: Path = typer.Argument(
        ...,
        help="Arquivo PDF ou pasta com PDFs.",
        exists=True,
    ),
    output: Path = typer.Option(
        Path("output"),
        "--output",
        "-o",
        help="Diretório de saída.",
    ),
    model: str = typer.Option(
        "mobile",
        "--model",
        "-m",
        help="Modelo: mobile (rápido) ou server (qualidade).",
    ),
    device: str = typer.Option(
        "auto",
        "--device",
        "-d",
        help="Dispositivo: auto, gpu ou cpu.",
    ),
    scale: int = typer.Option(
        2,
        "--scale",
        "-s",
        help="Escala de render: 1, 2 ou 3.",
    ),
    workers: Optional[int] = typer.Option(
        None,
        "--workers",
        "-w",
        help="Workers para render paralelo (default: auto).",
    ),
    mode: str = typer.Option(
        "text",
        "--mode",
        help="Modo: text (PP-OCRv5) ou structure (PP-StructureV3).",
    ),
    min_score: float = typer.Option(
        0.5,
        "--min-score",
        help="Score mínimo para filtrar textos.",
    ),
    verbose: bool = typer.Option(
        False,
        "--verbose",
        "-v",
        help="Output detalhado.",
    ),
):
    """Extrai texto de PDFs judiciais e gera Markdown."""
    from .config import OcrConfig
    from .engine import process_pdf
    from .progress import OcrProgress, print_summary
    from .writer import write_markdown

    config_kwargs = dict(
        model=model,
        device=device,
        scale=scale,
        mode=mode,
        min_score=min_score,
        output_dir=output,
        verbose=verbose,
    )
    if workers is not None:
        config_kwargs["workers"] = workers

    try:
        config = OcrConfig(**config_kwargs)
    except ValueError as e:
        console.print(f"[red]Erro de configuração:[/red] {e}")
        raise typer.Exit(1)

    # Descobrir PDFs
    if caminho.is_file():
        pdf_files = [caminho]
    elif caminho.is_dir():
        pdf_files = sorted(caminho.glob("*.pdf"))
        if not pdf_files:
            console.print(f"[yellow]Nenhum PDF encontrado em {caminho}[/yellow]")
            raise typer.Exit(1)
    else:
        console.print(f"[red]{caminho} não é um arquivo ou diretório válido.[/red]")
        raise typer.Exit(1)

    from .device import resolve_device

    resolved_device = resolve_device(config.device)
    console.print(f"[bold]tecjustica-ocr {__version__}[/bold]")
    console.print(f"  Dispositivo: {resolved_device}")
    console.print(f"  Modelo: {config.model} | Modo: {config.mode} | Escala: {config.scale}")
    console.print(f"  PDFs: {len(pdf_files)} | Output: {config.output_dir}")
    console.print()

    total_pages = 0
    total_texts = 0
    total_elapsed = 0.0

    for pdf_path in pdf_files:
        console.print(f"[bold cyan]Processando:[/bold cyan] {pdf_path.name}")

        with OcrProgress(verbose=config.verbose) as prog:
            from .renderer import get_page_count

            num_pages = get_page_count(pdf_path)
            prog.add_render_task(num_pages)
            prog.add_ocr_task(num_pages)

            result = process_pdf(
                pdf_path,
                config,
                on_render_progress=prog.update_render,
                on_ocr_progress=prog.update_ocr,
            )

            md_path = write_markdown(result, config.output_dir, mode=config.mode)
            elapsed = prog.elapsed

        total_pages += result.num_pages
        total_texts += result.total_texts
        total_elapsed += elapsed

        console.print(
            f"  [green]OK[/green] {result.num_pages} págs, "
            f"{result.total_texts} textos, {elapsed:.1f}s → {md_path}"
        )

    print_summary(len(pdf_files), total_pages, total_texts, total_elapsed)


@app.command()
def init(
    download: bool = typer.Option(
        True,
        "--download/--no-download",
        help="Baixar modelos automaticamente.",
    ),
    model: str = typer.Option(
        "all",
        "--model",
        "-m",
        help="Modelo para baixar: mobile, server ou all.",
    ),
):
    """Verifica compatibilidade do sistema e baixa modelos OCR."""
    from rich.panel import Panel
    from rich.table import Table

    from .doctor import download_models, run_all_checks

    console.print()
    console.print(
        Panel(
            f"[bold]tecjustica-ocr {__version__}[/bold] — Diagnóstico do sistema",
            border_style="blue",
        )
    )

    # Fase 1: Checagem do sistema
    console.print("\n[bold]1. Verificando sistema...[/bold]\n")
    checks = run_all_checks()

    table = Table(show_header=True, border_style="dim")
    table.add_column("Verificação", style="bold")
    table.add_column("Status", justify="center")
    table.add_column("Detalhe")

    required_failures = []
    warnings = []

    for check in checks:
        if check.ok:
            status = "[green]OK[/green]"
        elif check.required:
            status = "[red]FALHA[/red]"
            required_failures.append(check)
        else:
            status = "[yellow]AVISO[/yellow]"
            warnings.append(check)
        table.add_row(check.name, status, check.detail)

    console.print(table)

    # Diagnóstico final
    if required_failures:
        console.print(
            f"\n[red bold]Problemas encontrados ({len(required_failures)}):[/red bold]"
        )
        for f in required_failures:
            console.print(f"  [red]•[/red] {f.name}: {f.detail}")
        console.print(
            "\n[red]Corrija os problemas acima antes de usar o tecjustica-ocr.[/red]"
        )
        raise typer.Exit(1)

    if warnings:
        console.print(f"\n[yellow]Avisos ({len(warnings)}):[/yellow]")
        for w in warnings:
            console.print(f"  [yellow]•[/yellow] {w.name}: {w.detail}")

    # Fase 2: Download de modelos
    if download:
        console.print("\n[bold]2. Baixando modelos OCR...[/bold]\n")

        if model == "all":
            models_to_dl = ["mobile", "server"]
        else:
            models_to_dl = [model]

        from .device import resolve_device

        device = resolve_device("auto")

        with console.status("[bold cyan]Baixando e inicializando modelos..."):
            try:
                downloaded = download_models(models_to_dl, device=device)
                for m in downloaded:
                    console.print(f"  [green]OK[/green] Modelo {m} pronto")
            except RuntimeError as e:
                console.print(f"  [red]ERRO[/red] {e}")
                raise typer.Exit(1)

    # Fase 3: Resumo
    from .device import resolve_device

    device = resolve_device("auto")
    gpu_label = "[green]GPU[/green]" if "gpu" in device else "[yellow]CPU[/yellow]"

    console.print(
        Panel(
            f"[green bold]Sistema compatível![/green bold]\n\n"
            f"  Dispositivo: {gpu_label}\n"
            f"  Comando: [bold]tecjustica-ocr run <pdf>[/bold]\n\n"
            f"  Dica: use [bold]-m mobile[/bold] para velocidade\n"
            f"        use [bold]-m server[/bold] para qualidade",
            title="Pronto para usar",
            border_style="green",
        )
    )
