"""Live display for cheatly - continuously updating display."""

import time


from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel

from ..core.display import View
from ..core.environment import Environment
from ..core.pipeline import RenderPipeline


class LiveDisplay:
    """Display that updates continuously."""

    def __init__(
        self,
        pipeline: RenderPipeline,
        console: Console | None = None,
        refresh_interval: float = 0.5,
    ) -> None:
        """Initialize live display.

        Args:
            pipeline: Render pipeline to use
            console: Rich console
            refresh_interval: How often to refresh (seconds)
        """
        self.pipeline = pipeline
        self.console = console or Console()
        self.refresh_interval = refresh_interval
        self._running = False

    def show(
        self,
        initial_env: Environment,
        mode: str = "reference",
        focus: str | None = None,
        debug: bool = False,
    ) -> None:
        """Show live updating display.

        Args:
            initial_env: Initial environment
            mode: Display mode (reference, code, etc.)
            focus: Optional context to focus on
            debug: Show debug info
        """
        self._running = True

        our_pane = Environment.from_system().pane_id

        if initial_env.pane_id:
            target_pane = initial_env.pane_id
            locked = True
        else:
            target_pane = None
            locked = False

        try:
            with self.console.screen():
                with Live(
                    console=self.console,
                    auto_refresh=False,
                    screen=True,
                    refresh_per_second=int(1 / self.refresh_interval),
                ) as live:
                    while self._running:
                        if not locked:
                            current_env = Environment.from_system()
                            if (
                                current_env.pane_id != our_pane
                                and current_env.pane_id != target_pane
                            ):
                                target_pane = current_env.pane_id

                        if target_pane:
                            env = Environment.from_system(pane_id=target_pane)
                        else:
                            env = Environment.from_system()
                            env.pane_id = None

                        view = self.pipeline.render(
                            env, mode=mode, focus=focus, debug=debug
                        )

                        display = self._build_display(view, env)

                        live.update(display)
                        live.refresh()

                        time.sleep(self.refresh_interval)

        except KeyboardInterrupt:
            pass
        finally:
            self._running = False
            self.console.clear()

    def _build_display(self, view: View, env: Environment) -> Group:
        """Build complete display with status bar.

        Args:
            view: Rendered view
            env: Current environment

        Returns:
            Group with all display elements
        """
        elements = []

        status = self._build_status_bar(env)
        elements.append(status)
        elements.append("")

        if view.header:
            elements.append(view.header)
            elements.append("")

        elements.extend(view.content)

        if view.footer:
            elements.append("")
            elements.append(view.footer)

        return Group(*elements)

    def _build_status_bar(self, env: Environment) -> Panel:
        """Build status bar showing current state.

        Args:
            env: Current environment

        Returns:
            Status bar panel
        """
        parts = []

        if env.pane_id:
            parts.append(f"[cyan]Tracking:[/cyan] {env.pane_id}")
        else:
            parts.append("[yellow]Switch to another pane to track it[/yellow]")

        parts.append(f"[dim]{env.terminal_size[0]}×{env.terminal_size[1]}[/dim]")
        parts.append("[dim]Press Ctrl+C or q to quit[/dim]")

        status_text = "  │  ".join(parts)

        return Panel(
            status_text,
            style="dim",
            border_style="dim",
            height=3,
            title="[bold]Cheatly Live[/bold]",
            title_align="left",
        )
