//! Terminal kill operation.
//!
//! **Status**: Not yet implemented (TOOLS-TERM-04)
//!
//! This module will implement:
//! - Forceful process termination
//! - Cross-platform kill (SIGKILL/TerminateProcess)
//! - Idempotent kill operations

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

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

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

/// Forcefully terminate a terminal process.
///
/// **Status**: Implemented (TOOLS-TERM-04)
///
/// ## Implementation
///
/// This function:
/// 1. Looks up TerminalId in registry
/// 2. Gets process handle
/// 3. If already exited → returns success (idempotent)
/// 4. If still running:
///    - Sends forceful termination signal
///    - Unix: SIGKILL via `child.kill()`
///    - Windows: TerminateProcess via `child.kill()`
/// 5. Marks terminal as killed in registry
/// 6. Returns success
///
/// ## Idempotency
///
/// Multiple kill calls are safe:
/// - First call kills the process
/// - Subsequent calls return success (no-op)
/// - Does NOT remove from registry (use release for that)
///
/// ## Forceful Termination
///
/// This is a hard kill:
/// - Process cannot catch or ignore the signal
/// - No cleanup handlers run
/// - May leave resources in inconsistent state
///
/// Use when:
/// - Process is unresponsive
/// - Need immediate termination
/// - Timeout exceeded
///
/// ## Platform Notes
///
/// **Windows**:
/// - Uses TerminateProcess API
/// - May not kill child processes (no process tree kill)
/// - Test with long-running Windows commands
///
/// **Unix**:
/// - Sends SIGKILL
/// - Only kills direct child (not process group)
/// - Zombie processes may remain until wait()
///
/// ## Error Cases
///
/// - Invalid/unknown TerminalId → `ToolError::TerminalNotFound`
/// - Terminal released → `ToolError::TerminalNotFound`
///
/// ## See Also
///
/// - Task spec: `docs/building/04_acp_client/04_tasks_02_tools_and_sandboxing.md#TOOLS-TERM-04`
/// - Release terminal: `release.rs`
pub async fn kill_terminal(
    request: KillTerminalCommandRequest,
    _config: &TerminalConfig,
) -> ToolResult<KillTerminalCommandResponse> {
    use crate::terminal::registry::global_registry;

    let registry = global_registry();

    registry.get_mut(&request.terminal_id, |state| {
        // Check if already killed or exited
        if state.killed || state.exit_status.is_some() {
            // Already terminated, return success (idempotent)
            tracing::debug!(
                terminal_id = %request.terminal_id,
                "Terminal already terminated"
            );
            return;
        }

        // Kill the process
        match state.process.start_kill() {
            Ok(()) => {
                state.killed = true;
                tracing::info!(
                    terminal_id = %request.terminal_id,
                    "Terminal process killed"
                );
            }
            Err(e) => {
                // If kill fails, it might already be dead
                tracing::warn!(
                    terminal_id = %request.terminal_id,
                    error = %e,
                    "Failed to kill terminal (process may already be dead)"
                );
                state.killed = true;
            }
        }
    })?;

    Ok(KillTerminalCommandResponse {})
}
