use std::sync::OnceLock;
use serde::Serialize;
use tokio::fs;

static DEEPSEEK_TOKEN: OnceLock<String> = OnceLock::new();

async fn deepseek_token() -> Result<String, std::io::Error> {
    if let Some(token) = DEEPSEEK_TOKEN.get() {
        return Ok(token.clone());
    }
    let raw = fs::read_to_string("deepseek.txt").await?;
    let token = raw.trim().to_string();
    let _ = DEEPSEEK_TOKEN.set(token.clone());
    Ok(token)
}

#[derive(Serialize)]
struct Message<'a> {
    role: &'a str,
    content: &'a str,
}

#[derive(Serialize)]
struct ChatRequest<'a> {
    model: &'a str,
    messages: Vec<Message<'a>>,
    stream: bool,
}

pub async fn ask_deepseek() -> Result<(), Box<dyn std::error::Error>> {
    let token = deepseek_token().await?;
    let payload = ChatRequest {
        model: "deepseek-chat",
        messages: vec![
            Message {
                role: "system",
                content: "You are a helpful assistant.",
            },
            Message {
                role: "user",
                content: "Hello!",
            },
        ],
        stream: false,
    };

    let response = reqwest::Client::new()
        .post("https://api.deepseek.com/chat/completions")
        .bearer_auth(token)
        .json(&payload)
        .send()
        .await?;

    let status = response.status();
    let body = response.text().await?;
    println!("DeepSeek status: {status}");
    println!("{body}");
    Ok(())
}
