"""Global mutable state shared across terminal, UI, and agent.

Created once in the App and passed by reference to AgentBrain
and UI widgets.

v0.9.0: Step tracking replaced with terminal widget reference.
The agent reads terminal output via snapshot_terminal() instead
of the old log_buffer.
"""

from __future__ import annotations

import asyncio
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from .ui.terminal_widget import TerminalWidget


@dataclass
class InstallState:
    """Shared mutable state for the installer lifecycle."""

    # -- Terminal widget reference (set after compose) --
    terminal: Optional[TerminalWidget] = field(default=None, repr=False)

    # -- High-level status --
    is_running: bool = False
    is_complete: bool = False
    has_error: bool = False

    # -- Main event loop reference (for agent thread -> main loop calls) --
    main_loop: Optional[asyncio.AbstractEventLoop] = None

    # -- Agent is currently investigating an error --
    agent_investigating: bool = False

    # -- Timestamp of last terminal output (for stall detection) --
    last_output_time: float = 0.0

    def snapshot_terminal(self) -> str:
        """Return the recent terminal output for agent prompt injection."""
        if self.terminal is None:
            return "(terminal not started)"
        return self.terminal.get_recent_output(max_lines=150)

    def snapshot_screen(self) -> str:
        """Return the current visible terminal screen."""
        if self.terminal is None:
            return "(terminal not started)"
        return self.terminal.get_screen_text()
