"""
Rich terminal output formatting voor Elephate CLI

Bevat functies voor:
- Progress bars
- Tabellen
- Gestylde output met Elephate huisstijl
"""

import time
from typing import List, Dict, Any, Optional

from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
from rich.text import Text
from rich import box

from .parser import PDFInfo, DocumentType


# Elephate huisstijl kleuren
ELEPHATE_BLUE = "#1057a0"
ELEPHATE_DARK_BLUE = "#044395"
ELEPHATE_LIGHT_BLUE = "#6387bb"
ELEPHATE_BABY_BLUE = "#b5c7df"

console = Console()


def print_header(version: str = "0.1.0"):
    """Print de Elephate CLI header"""
    header = Panel(
        Text.from_markup(f"[bold {ELEPHATE_BLUE}]Calculatie Copilot[/]"),
        title=f"[bold]Elephate CLI v{version} (mockup)[/]",
        border_style=ELEPHATE_BLUE,
        padding=(0, 2)
    )
    console.print(header)
    console.print()


def print_files_found(pdf_files: List[PDFInfo]):
    """Print gevonden bestanden met classificatie"""
    console.print(f"[bold]Gevonden bestanden:[/] {len(pdf_files)}")

    for pdf in pdf_files:
        doc_type_str = "[green]PDF_TEXT[/]" if pdf.doc_type == DocumentType.PDF_TEXT else "[yellow]TECH_DRAWING[/]"
        if pdf.doc_type == DocumentType.UNKNOWN:
            doc_type_str = "[red]UNKNOWN[/]"

        pages_str = f"{pdf.num_pages} pagina" + ("'s" if pdf.num_pages != 1 else "")

        console.print(f"   [dim]•[/] {pdf.filename:<40} {doc_type_str:<20} {pages_str}")

    console.print()


def simulate_processing(pdf_files: List[PDFInfo], delay: float = 0.05) -> Dict[str, int]:
    """
    Simuleer verwerking met progress bars.

    Returns:
        Dict met statistieken
    """
    text_docs = [f for f in pdf_files if f.doc_type == DocumentType.PDF_TEXT]
    drawing_docs = [f for f in pdf_files if f.doc_type == DocumentType.TECH_DRAWING]

    total_pages = sum(f.num_pages for f in pdf_files)
    total_tiles = sum(f.num_pages * 4 for f in drawing_docs)  # Geschat 4 tiles per pagina

    console.print("[bold]Verwerken...[/]")

    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(complete_style=ELEPHATE_BLUE),
        TaskProgressColumn(),
        console=console
    ) as progress:

        # Tekst extractie
        if text_docs:
            text_task = progress.add_task(
                "[cyan]Tekst extractie[/]",
                total=sum(f.num_pages for f in text_docs)
            )
            for pdf in text_docs:
                for _ in range(pdf.num_pages):
                    time.sleep(delay)
                    progress.advance(text_task)

        # Tekening analyse
        if drawing_docs:
            drawing_task = progress.add_task(
                "[yellow]Tekening analyse[/]",
                total=len(drawing_docs) * 4  # Stappen per tekening
            )
            for pdf in drawing_docs:
                for _ in range(4):
                    time.sleep(delay)
                    progress.advance(drawing_task)

        # Categorie detectie
        cat_task = progress.add_task(
            "[green]Categorie detectie[/]",
            total=7  # 7 STABU categorieën
        )
        for _ in range(7):
            time.sleep(delay * 2)
            progress.advance(cat_task)

    console.print()

    return {
        "total_pages": total_pages,
        "total_tiles": total_tiles,
        "text_docs": len(text_docs),
        "drawing_docs": len(drawing_docs)
    }


def print_results_table(results: Dict[str, Any]):
    """Print resultaten in een mooie tabel"""
    console.print("[bold]Resultaten (MOCK DATA):[/]")

    table = Table(
        box=box.ROUNDED,
        border_style=ELEPHATE_LIGHT_BLUE,
        header_style=f"bold {ELEPHATE_BLUE}",
        show_lines=False
    )

    table.add_column("Categorie", style="white", min_width=28)
    table.add_column("Items", justify="right", style="cyan")
    table.add_column("Kosten", justify="right", style="green")
    table.add_column("Uren", justify="right", style="yellow")

    categories = results.get("categories", {})

    for cat_code in sorted(categories.keys()):
        cat_data = categories[cat_code]
        summary = cat_data.get("summary", {})

        table.add_row(
            cat_data.get("category", f"{cat_code} Onbekend"),
            str(summary.get("total_items", 0)),
            format_currency(summary.get("total_cost", 0)),
            format_hours(summary.get("total_labor_hours", 0))
        )

    # Totaal rij
    totals = results.get("totals", {})
    table.add_section()
    table.add_row(
        "[bold]TOTAAL[/]",
        f"[bold]{totals.get('total_items', 0)}[/]",
        f"[bold green]{format_currency(totals.get('total_cost', 0))}[/]",
        f"[bold yellow]{format_hours(totals.get('total_labor_hours', 0))}[/]"
    )

    console.print(table)
    console.print()


def print_mock_warning():
    """Print waarschuwing dat dit mock data is"""
    console.print(
        Panel(
            "[yellow]Dit zijn mock resultaten - geen echte LLM analyse[/]",
            border_style="yellow",
            padding=(0, 1)
        )
    )
    console.print()


def print_token_usage(token_data: Dict[str, Any]):
    """Print token usage information after calculation results."""
    console.print("[bold]Token Gebruik (MOCK):[/]")

    calc = token_data.get("calculation", {})
    daily = token_data.get("daily_usage", {})

    # Create a mini table for token stats
    table = Table(
        box=box.SIMPLE,
        show_header=False,
        padding=(0, 1)
    )
    table.add_column("Metric", style="dim")
    table.add_column("Value", style="cyan", justify="right")

    table.add_row("Input tokens", format_tokens(calc.get("input_tokens", 0)))
    table.add_row("Output tokens", format_tokens(calc.get("output_tokens", 0)))
    table.add_row("Totaal", format_tokens(calc.get("total_tokens", 0)))
    table.add_row("Geschatte kosten", f"€ {calc.get('estimated_cost', 0):.4f}")

    console.print(table)

    # Daily usage bar
    used = daily.get("used", 0)
    total = daily.get("total", 10000)
    percentage = daily.get("percentage", 0)

    console.print()
    console.print(f"  [dim]Dagelijks:[/] {format_tokens(used)} / {format_tokens(total)} tokens ({percentage}%)")

    # Visual progress bar
    bar_width = 30
    filled = min(int(bar_width * percentage / 100), bar_width)
    bar = "[" + "=" * filled + " " * (bar_width - filled) + "]"

    color = "green" if percentage < 50 else "yellow" if percentage < 80 else "red"
    console.print(f"  [{color}]{bar}[/]")
    console.print(f"  [dim]Reset: {daily.get('reset_time', 'onbekend')}[/]")
    console.print()


def format_tokens(count: int) -> str:
    """Format token count with Dutch thousands separator."""
    return f"{count:,}".replace(",", ".")


def print_export_info(output_dir: str, files: List[str]):
    """Print informatie over geëxporteerde bestanden"""
    console.print("[bold]Resultaat opgeslagen:[/]")
    for file in files:
        console.print(f"   [dim]->[/] {file}")
    console.print()


def print_error(message: str):
    """Print een error bericht"""
    console.print(f"[bold red]Error:[/] {message}")


def print_success(message: str):
    """Print een success bericht"""
    console.print(f"[bold green][OK][/] {message}")


def print_info(message: str):
    """Print een info bericht"""
    console.print(f"[dim][i][/] {message}")


def format_currency(amount: float) -> str:
    """Formatteer een bedrag als Euro"""
    return f"€ {amount:,.2f}".replace(",", " ").replace(".", ",").replace(" ", ".")


def format_hours(hours: float) -> str:
    """Formatteer uren"""
    return f"{hours:,.1f}".replace(",", " ").replace(".", ",").replace(" ", ".")
