//! Terminal release operation for resource cleanup.
//!
//! **Status**: Not yet implemented (TOOLS-TERM-05)
//!
//! This module will implement:
//! - Terminal resource cleanup
//! - Process termination if still running
//! - Registry removal

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

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

/// Response from releasing a terminal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseTerminalResponse {}

/// Release terminal resources and clean up.
///
/// **Status**: Implemented (TOOLS-TERM-05)
///
/// ## Implementation
///
/// This function:
/// 1. Looks up TerminalId in registry
/// 2. If not found → returns error
/// 3. If process still running:
///    - Kills process forcefully
///    - Waits briefly for exit
/// 4. Aborts output capture task
/// 5. Removes from registry:
///    - Drops process handle
///    - Frees ring buffer memory
///    - Invalidates TerminalId
/// 6. Returns success
///
/// ## Resource Cleanup
///
/// Frees:
/// - Process handle (Child)
/// - Output capture task (JoinHandle)
/// - Ring buffer memory
/// - Registry entry
///
/// ## Behavior
///
/// - Kills process if still running (no confirmation)
/// - Frees all associated memory
/// - Subsequent operations on this TerminalId will fail with TerminalNotFound
///
/// ## When to Release
///
/// Release when:
/// - Process has completed and output is no longer needed
/// - Need to free memory (long-running session)
/// - Cleaning up after error
///
/// Do NOT release if:
/// - Output may be needed later
/// - Process should keep running (use kill instead)
///
/// ## Error Cases
///
/// - Invalid/unknown TerminalId → `ToolError::TerminalNotFound`
///
/// ## See Also
///
/// - Task spec: `docs/building/04_acp_client/04_tasks_02_tools_and_sandboxing.md#TOOLS-TERM-05`
/// - Kill terminal: `kill.rs`
pub async fn release_terminal(
    request: ReleaseTerminalRequest,
    _config: &TerminalConfig,
) -> ToolResult<ReleaseTerminalResponse> {
    use crate::terminal::registry::global_registry;

    let registry = global_registry();

    // Remove terminal from registry
    let mut state = registry.remove(&request.terminal_id)?;

    // Kill process if still running
    if !state.killed && state.exit_status.is_none() {
        let _ = state.process.start_kill();
        // Wait briefly for the process to die
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        let _ = state.process.wait().await;
    }

    // Abort output capture task if it exists
    if let Some(task) = state.output_task.take() {
        task.abort();
    }

    tracing::info!(
        terminal_id = %request.terminal_id,
        "Terminal resources released"
    );

    Ok(ReleaseTerminalResponse {})
}
