//! `voice_inbound_transform` — fires on every inbound turn.
//!
//! Returns `system_addendum` teaching the LLM the SSML markers
//! when voice mode is active for the conversation. Passthrough
//! when the toggle is off.

use serde::Deserialize;
use serde_json::{json, Value};

use super::VoiceToolContext;
use crate::error::{Result, VoiceError};
use nexo_tool_meta::voice_addenda::voice_mode_addendum;
use nexo_tool_meta::Locale;
use std::str::FromStr;

#[derive(Debug, Deserialize)]
struct Args {
    context: InboundContext,
}

#[derive(Debug, Deserialize)]
struct InboundContext {
    conversation_key: String,
    #[serde(default)]
    language: Option<String>,
    #[serde(default)]
    #[allow(dead_code)]
    inbound_kind: Option<String>,
}

pub async fn handle(ctx: &VoiceToolContext, args: Value) -> Result<Value> {
    let parsed: Args = serde_json::from_value(args)
        .map_err(|e| VoiceError::InvalidParam(format!("voice_inbound_transform: {e}")))?;
    match ctx.store.get_active(&parsed.context.conversation_key).await {
        Ok(Some(_row)) => {
            let locale = parsed
                .context
                .language
                .as_deref()
                .and_then(|s| Locale::from_str(s).ok());
            let addendum = voice_mode_addendum(locale.as_ref());
            Ok(json!({ "ok": true, "system_addendum": addendum }))
        }
        _ => Ok(json!({ "ok": true, "passthrough": true })),
    }
}
