import Foundation
import NucleicProtocol

extension MacVMEngine {
    /// Drain nash's spooled shell-event batches out of a **Linux** guest (docs/NASH.md §6.2, §7.4, M4).
    ///
    /// nash is the forced default shell in the guest (via narOS's `/bin/sh`→nash divert), but inside a
    /// VM it can't reach the host's control socket the way container nash does — so it spools each
    /// `shell-batch` as a line of JSONL under `/var/spool/nucleic-nash/*.jsonl`. The guest agent's
    /// `shell-events` op hands those lines back (base64) and truncates what it returns; the host polls it
    /// after each `linux_vm_exec` and feeds the batches into the same `/shell-event` ingestion path the
    /// container surface uses. This is the "host poll" half of the M4 drain.
    ///
    /// Best-effort and non-throwing (observation must never perturb the exec path — §5.5): a guest with
    /// no agent, no nash, or an empty spool returns `[]`, and any transport error is swallowed (and
    /// discards the channel so the next drain re-probes). Each returned `JSONValue` is one decoded
    /// `shell-batch` object, ready for ``MCPApprovalServer/parseShellBatch(_:)``.
    func drainShellEvents(name: String) async -> [JSONValue] {
        guard let client = await agentClient(name: name) else { return [] }
        let reply: JSONValue
        do {
            reply = try await client.request(
                op: MacVMAgentWire.ShellEvents.op,
                fields: [MacVMAgentWire.ShellEvents.truncateKey: .number(1)],
                timeout: 5)
        } catch {
            // An op-level `agentError` (older guest without the op) leaves the channel usable; a real
            // transport failure discards it so the next poll re-probes the (possibly restarted) agent.
            if let agentError = error as? MacVMAgentError, agentError.isTransportFailure {
                await discardAgentClient(name: name, client)
            }
            return []
        }
        let b64 = reply[MacVMAgentWire.ShellEvents.eventsKey]?.stringValue ?? ""
        return MacVMAgentWire.ShellEvents.decodeBatches(base64: b64)
    }
}
