//! `spool hook <subcommand>` command handlers.
//!
//! Thin glue between clap arg structs and `hook_runtime` entry points.
//! Each handler wraps the actual hook in [`hook_runtime::run_silent`]
//! so any internal failure becomes a stderr log + exit 0 (D7).

use crate::cli::args::{
    HookArgs, HookCommand, HookPostToolUseArgs, HookSessionStartArgs, HookSimpleArgs, HookStopArgs,
};
use crate::domain::WakeupProfile;
use crate::hook_runtime::{self, post_tool_use, pre_compact, session_start, stop, user_prompt};

pub fn execute(args: HookArgs) -> anyhow::Result<()> {
    match args.command {
        HookCommand::SessionStart(a) => execute_session_start(a),
        HookCommand::UserPrompt(a) => execute_user_prompt(a),
        HookCommand::PostToolUse(a) => execute_post_tool_use(a),
        HookCommand::Stop(a) => execute_stop(a),
        HookCommand::PreCompact(a) => execute_pre_compact(a),
    }
}

fn execute_session_start(args: HookSessionStartArgs) -> anyhow::Result<()> {
    hook_runtime::run_silent("session-start", || {
        session_start::run(session_start::SessionStartArgs {
            config_path: args.config,
            cwd: args.cwd,
            task: args.task,
            profile: WakeupProfile::from(args.profile),
        })
    });
    Ok(())
}

fn execute_user_prompt(args: HookSimpleArgs) -> anyhow::Result<()> {
    hook_runtime::run_silent("user-prompt", || {
        user_prompt::run(user_prompt::UserPromptArgs {
            config_path: args.config,
            cwd: args.cwd,
            prompt_override: None,
        })
    });
    Ok(())
}

fn execute_post_tool_use(args: HookPostToolUseArgs) -> anyhow::Result<()> {
    hook_runtime::run_silent("post-tool-use", || {
        post_tool_use::run(post_tool_use::PostToolUseArgs {
            config_path: args.config,
            cwd: args.cwd,
            tool_name: args.tool_name,
            payload: args.payload,
        })
    });
    Ok(())
}

fn execute_stop(args: HookStopArgs) -> anyhow::Result<()> {
    hook_runtime::run_silent("stop", || {
        stop::run(stop::StopArgs {
            config_path: args.config,
            cwd: args.cwd,
            transcript_path: args.transcript_path,
            hook_input: args.hook_input,
            home: args.home,
        })
        .map(|_report| ())
    });
    Ok(())
}

fn execute_pre_compact(args: HookSimpleArgs) -> anyhow::Result<()> {
    hook_runtime::run_silent("pre-compact", || {
        pre_compact::run(pre_compact::PreCompactArgs {
            config_path: args.config,
            cwd: args.cwd,
            context_override: None,
        })?;
        Ok(())
    });
    Ok(())
}
