//! `voice_language_style_inbound_transform` — fires on every inbound
//! turn regardless of voice-mode toggle.
//!
//! Returns the dialect / vocabulary guidance addendum keyed by the
//! conversation's locale (voseo for `es-AR`, vosotros for `es-ES`,
//! British vocab for `en-GB`, Spanglish loanwords for `es-US`, …).
//! Locks the LLM into the configured register without requiring the
//! per-conversation voice toggle to be active.
//!
//! Phase voice-plugin-extract SDK-parity gap 1 — mirrors the SDK
//! microapp's `language_style_inbound_transform` tool (registered
//! separately from voice_mode in agent-creator-microapp/src/main.rs).

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

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

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

#[derive(Debug, Deserialize)]
struct InboundContext {
    #[serde(default)]
    #[allow(dead_code)]
    conversation_key: Option<String>,
    #[serde(default)]
    language: 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_language_style_inbound_transform: {e}"))
    })?;
    let locale = parsed
        .context
        .language
        .as_deref()
        .and_then(|s| Locale::from_str(s).ok());
    match language_style_addendum(locale.as_ref()) {
        Some(addendum) => Ok(json!({ "ok": true, "system_addendum": addendum })),
        None => Ok(json!({ "ok": true, "passthrough": true })),
    }
}
