"""Render pipeline for cheatly - stateless transformation from environment to view."""

from rich.align import Align
from rich.panel import Panel

from .environment import Environment
from ..detectors import detect_contexts, get_activation_hints
from .display import View
from ..models import Context, Sheet
from ..parser import SheetParser
from ..renderers import get_renderer

from termcards import sheets


class RenderPipeline:
    """Stateless pipeline that transforms environment → contexts → sheets → view."""

    def __init__(self) -> None:
        """Initialize the pipeline components."""
        self.parser = SheetParser()

    def render(
        self,
        env: Environment,
        mode: str = "reference",
        focus: str | None = None,
        debug: bool = False,
        specific_sheet: str | None = None,
    ) -> View:
        """Render a view from environment using mode-specific renderer.

        Args:
            env: Environment data
            mode: Display mode (reference, code, etc.)
            focus: Optional context to focus on
            debug: Show debug info
            specific_sheet: Load only this specific sheet

        Returns:
            View ready to display
        """
        view = View()

        renderer = get_renderer(mode)
        if not renderer:
            view.content = [
                Panel(
                    f"[red]Unknown mode: {mode}[/red]\n"
                    f"Available modes: reference, code",
                    border_style="red",
                )
            ]
            return view

        if specific_sheet:
            sheet = self._load_specific_sheet(specific_sheet)
            if sheet:
                if sheet.mode == mode:
                    sheets = [sheet]
                else:
                    sheets = []
                contexts = []
            else:
                view.content = [
                    Panel(
                        f"[red]Sheet not found: {specific_sheet}[/red]",
                        border_style="red",
                    )
                ]
                return view
        else:
            contexts = detect_contexts(env)
            sheets = self._load_sheets_for_mode(contexts, mode)

        if not sheets:
            view.is_empty = True
            view.content = [self._build_empty_message(mode)]
            return view

        view.content = renderer.render(sheets, env.terminal_size, focus)

        if debug:
            view.header = self._build_debug_header(env, contexts, sheets, mode)

        return view

    def _load_specific_sheet(self, name: str) -> Sheet | None:
        """Load a specific sheet by name using centralized discovery."""
        result = sheets.find_sheet_any_type(name)
        if result:
            path, sheet_type = result
            return self.parser.parse(path, sheet_type)
        return None

    def _load_sheets_for_mode(self, contexts: list[Context], mode: str) -> list[Sheet]:
        """Load sheets for detected contexts, filtered by mode."""
        sheet_list = []
        loaded_sheets = set()
        sheet_type = "code" if mode == "code" else "reference"

        for ctx in contexts:
            sheet_name = ctx.sheet or ctx.name
            if sheet_name in loaded_sheets:
                continue

            sheet_path = sheets.find_sheet(sheet_name, sheet_type)
            if sheet_path:
                sheet = self.parser.parse(sheet_path, sheet_type)
                if sheet and sheet.mode == mode:
                    sheet_list.append(sheet)
                    loaded_sheets.add(sheet_name)
        return sheet_list

    def _build_empty_message(self, mode: str) -> Align:
        """Build empty state message for mode with dynamic hints."""
        hints = get_activation_hints(mode)

        if mode == "code":
            message = "[dim]No code examples to display.\n\n"
        else:
            message = "[dim]No cheatsheets to display.\n\n"

        if hints:
            message += "Try:\n"
            message += "\n".join(hints)
        else:
            message += "Try:\n"
            message += "  • Using --sheet to specify a sheet\n"
            message += "  • Using --help to see options"

        message += "[/dim]"

        return Align.center(
            Panel(
                message,
                border_style="dim",
                title=f"[yellow]No {mode.title()} Content[/yellow]",
            ),
            vertical="middle",
        )

    def _build_debug_header(
        self, env: Environment, contexts: list[Context], sheets: list[Sheet], mode: str
    ) -> Panel:
        """Build debug info header."""
        debug_info = []
        debug_info.append(f"Terminal: {env.terminal_size[0]}×{env.terminal_size[1]}")
        debug_info.append(f"Mode: {mode}")
        debug_info.append(f"Sheets: {len(sheets)}")
        debug_info.append(f"Contexts: {', '.join(c.name for c in contexts)}")
        if env.pane_id:
            debug_info.append(f"Pane: {env.pane_id}")

        return Panel(
            " | ".join(debug_info),
            border_style="blue",
            title="[bold]Debug Info[/bold]",
            height=3,
        )
