"""Shared context passed to commands and components."""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from clients.terminal.state import StateManager
    from clients.terminal.tui.chat_model import ChatModel
    from clients.terminal.tui.settings import TuiSettings
    from clients.terminal.tui.widgets.chat_panel import ChatPanel
    from clients.terminal.tui.widgets.status_panel import StatusPanel
    from clients.terminal.ws_client import NaviWebSocketClient


@dataclass
class TuiContext:
    """Mutable bag of services and widgets available to commands."""

    session_id: str | None = None
    profile_id: str | None = None
    ws_client: "NaviWebSocketClient | None" = None
    state: "StateManager | None" = None
    settings: "TuiSettings | None" = None
    chat_panel: "ChatPanel | None" = None
    status_panel: "StatusPanel | None" = None
    chat_model: "ChatModel | None" = None
    cwd: Path = field(default_factory=lambda: Path.cwd().resolve())

    def app(self):
        """Return the running TuiApp instance."""
        from textual import app as textual_app

        # active_app is a ContextVar containing the currently running App.
        return textual_app.active_app.get()
