"""Brewing timer — live countdown in the terminal using rich."""

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

# ---------------------------------------------------------------------------
# Brew time definitions (seconds)
# ---------------------------------------------------------------------------

BREW_TIMES: Dict[str, Dict] = {
    "espresso":    {"label": "Espresso",    "seconds": 30,    "emoji": "💪"},
    "americano":   {"label": "Americano",   "seconds": 90,    "emoji": "☕"},
    "latte":       {"label": "Latte",       "seconds": 210,   "emoji": "🥛"},
    "cappuccino":  {"label": "Cappuccino",  "seconds": 210,   "emoji": "☕"},
    "pour-over":   {"label": "Pour Over",   "seconds": 240,   "emoji": "☕"},
    "french-press": {"label": "French Press", "seconds": 240, "emoji": "☕"},
    "cold-brew":   {"label": "Cold Brew",   "seconds": 43200, "emoji": "🧊"},
    "mocha":       {"label": "Mocha",       "seconds": 210,   "emoji": "🍫"},
    "macchiato":   {"label": "Macchiato",   "seconds": 90,    "emoji": "☕"},
    "flat-white":  {"label": "Flat White",  "seconds": 210,   "emoji": "☕"},
}

_LONG_BREW_THRESHOLD = 600  # seconds; brews longer than this skip the live timer


def run_timer(
    brew_type: str = "french-press",
    sleep_fn: Optional[Callable[[float], None]] = None,
) -> None:
    """
    Run an interactive brewing countdown timer.

    Args:
        brew_type:  Key from BREW_TIMES (e.g. 'french-press').
        sleep_fn:   Override for time.sleep — useful in tests.
    """
    # Import rich here so the module is still importable without rich for tests.
    from rich.console import Console
    from rich.live import Live
    from rich.panel import Panel
    from rich.progress import (
        BarColumn,
        Progress,
        SpinnerColumn,
        TaskProgressColumn,
        TimeRemainingColumn,
    )

    _sleep = sleep_fn if sleep_fn is not None else time.sleep
    console = Console()

    brew_info = BREW_TIMES.get(brew_type, BREW_TIMES["french-press"])
    total_seconds = brew_info["seconds"]
    label = brew_info["label"]
    emoji = brew_info["emoji"]

    if total_seconds > _LONG_BREW_THRESHOLD:
        hours = total_seconds / 3600
        console.print(
            f"\n[yellow]{emoji} {label} takes ~{hours:.0f} hours. "
            f"Set a reminder and come back later![/yellow]\n"
        )
        return

    progress = Progress(
        SpinnerColumn(),
        "[progress.description]{task.description}",
        BarColumn(),
        TaskProgressColumn(),
        TimeRemainingColumn(),
    )

    panel = Panel(progress, title=f"{emoji} Brewing {label}", border_style="yellow")

    with Live(panel, refresh_per_second=4):
        task = progress.add_task(f"[cyan]Brewing…", total=total_seconds)
        for _ in range(total_seconds):
            _sleep(1)
            progress.advance(task)

    console.print(
        Panel(
            f"[bold green]✓ Your {label} is ready! Enjoy! {emoji}[/bold green]",
            border_style="green",
        )
    )


def list_brew_times() -> None:
    """Print a table of all available brew types and their times."""
    from rich.console import Console
    from rich.table import Table

    from .coffee_types import COFFEE_TYPES

    console = Console()
    table = Table(title="☕ Brewing Times", border_style="yellow", show_lines=True)
    table.add_column("Type", style="cyan", no_wrap=True)
    table.add_column("Brew Time", justify="right")
    table.add_column("Caffeine", justify="right")
    table.add_column("Intensity")

    for key, info in BREW_TIMES.items():
        coffee = COFFEE_TYPES.get(key, {})
        caffeine = str(coffee.get("caffeine_mg", "?")) + "mg"
        intensity = coffee.get("intensity", "?").capitalize()

        secs = info["seconds"]
        if secs > _LONG_BREW_THRESHOLD:
            time_str = f"{secs // 3600}h+"
        elif secs >= 60:
            m, s = divmod(secs, 60)
            time_str = f"{m}m {s}s" if s else f"{m}m"
        else:
            time_str = f"{secs}s"

        table.add_row(info["label"], time_str, caffeine, intensity)

    console.print(table)


def get_brew_type_choices() -> List[str]:
    """Return list of valid brew type keys."""
    return list(BREW_TIMES.keys())
