//! Terminal output retrieval from ring buffer.
//!
//! **Status**: Not yet implemented (TOOLS-TERM-02)
//!
//! This module will implement:
//! - Output snapshot retrieval
//! - Truncation flag tracking
//! - Exit status reporting

use crate::config::TerminalConfig;
use crate::error::ToolResult;
use serde::{Deserialize, Serialize};

/// Request to get terminal output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerminalOutputRequest {
    /// Terminal ID from create response.
    pub terminal_id: String,
}

/// Response with terminal output snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerminalOutputResponse {
    /// UTF-8 output (stdout + stderr interleaved).
    pub output: String,

    /// Whether output was truncated due to buffer overflow.
    pub truncated: bool,

    /// Exit status if process has completed (None if still running).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_status: Option<i32>,
}

/// Get current output from a terminal's ring buffer.
///
/// **Status**: Implemented (TOOLS-TERM-02)
///
/// ## Implementation
///
/// This function:
/// 1. Looks up TerminalId in registry
/// 2. Locks ring buffer (thread-safe access)
/// 3. Reads current contents (snapshot, not consuming)
/// 4. Gets truncation flag from buffer
/// 5. Checks process status for exit_status
/// 6. Returns TerminalOutputResponse
///
/// ## Behavior
///
/// - Returns current output snapshot (cumulative)
/// - Does NOT consume output (multiple calls return same data)
/// - Truncation flag indicates if any output was dropped
/// - Exit status available only after process completes
///
/// ## Error Cases
///
/// - Invalid/unknown TerminalId → `ToolError::TerminalNotFound`
/// - Terminal released → `ToolError::TerminalNotFound`
///
/// ## Use Cases
///
/// - Poll for output while process is running
/// - Check progress without blocking
/// - Get final output after completion
///
/// ## See Also
///
/// - Task spec: `docs/building/04_acp_client/04_tasks_02_tools_and_sandboxing.md#TOOLS-TERM-02`
/// - Wait for exit: `wait.rs`
pub async fn get_terminal_output(
    request: TerminalOutputRequest,
    _config: &TerminalConfig,
) -> ToolResult<TerminalOutputResponse> {
    use crate::terminal::registry::global_registry;

    let registry = global_registry();

    // Look up terminal and get output
    registry.get_mut(&request.terminal_id, |state| {
        // Lock output buffer and get snapshot
        let buffer = state.output_buffer.lock().unwrap();
        let output = buffer.snapshot();
        let truncated = buffer.is_truncated();

        // Check if process has exited
        let exit_status = state.exit_status.as_ref().map(|status| {
            #[cfg(unix)]
            {
                use std::os::unix::process::ExitStatusExt;
                status.code().or_else(|| status.signal()).unwrap_or(-1)
            }
            #[cfg(not(unix))]
            {
                status.code().unwrap_or(-1)
            }
        });

        TerminalOutputResponse {
            output,
            truncated,
            exit_status,
        }
    })
}
