import SwiftUI

/// A one-shot channel for running a command in the session's in-app terminal. The
/// in-chat "Log in" button on an authentication error writes `claude /login` here;
/// `TerminalPanel` observes it and types the command into the live shell once it's
/// ready — so the user can re-authenticate without opening a separate terminal.
///
/// App-wide (one visible terminal per open chat). Each request carries a fresh `id`
/// so the terminal types it exactly once and a plain redraw never replays the last
/// command.
@MainActor
@Observable
final class TerminalCommandBus {
    /// The command queued to run, or nil once the terminal has typed it.
    private(set) var pending: Pending?

    struct Pending: Identifiable, Equatable {
        let id = UUID()
        let command: String
    }

    /// Queue `command` to run in the visible terminal (a trailing return is added when
    /// it's typed). Replaces any still-pending command.
    func run(_ command: String) { pending = Pending(command: command) }

    /// Clear `id` after the terminal has typed it, so it isn't replayed on the next redraw.
    func consume(_ id: UUID) { if pending?.id == id { pending = nil } }
}
