use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
struct LlamaCppResponse {
    choices: Vec<LlamaCppChoice>,
}

#[derive(Debug, Deserialize, Serialize)]
struct LlamaCppChoice {
    message: LlamaCppMessage,
}

#[derive(Debug, Deserialize, Serialize)]
struct LlamaCppMessage {
    content: String,
}

/// Translates text using local llama.cpp server running Gemma 4.
#[tauri::command]
pub async fn translate_text(
    text: String,
    #[allow(non_snake_case)] target_lang: String,
) -> Result<String, String> {
    if text.trim().is_empty() {
        return Ok(String::new());
    }

    println!("[Translate] Request: {} -> {}", target_lang, text);

    let client = reqwest::Client::new();

    let prompt = format!(
        "Translate the following text into {}. Only output the translated text without any additional context or notes.\n\nText: {}",
        target_lang, text
    );

    // llama.cpp server endpoint (compatible with OpenAI API format)
    let payload = serde_json::json!({
        "model": "gemma4",
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "stream": false,
        "temperature": 0.1
    });

    println!("[Translate] Sending to llama.cpp server...");

    let response = client
        .post("http://127.0.0.1:8081/v1/chat/completions")
        .header("Content-Type", "application/json")
        .json(&payload)
        .send()
        .await
        .map_err(|e| {
            format!(
                "llama.cpp server request failed: {}. Ensure the server is running at port 8081.",
                e
            )
        })?;

    if !response.status().is_success() {
        return Err(format!("llama.cpp server error: {}", response.status()));
    }

    let json: LlamaCppResponse = response
        .json()
        .await
        .map_err(|e| format!("Parse error: {}", e))?;

    println!("[Translate] Response received");

    if let Some(choice) = json.choices.first() {
        Ok(choice.message.content.trim().to_string())
    } else {
        Err("No translation result returned".to_string())
    }
}
