//! {{AGENT_NAME}} — SentryAgent.ai agent starter (Rust)
//! Agent ID: {{AGENT_ID}}

use std::collections::HashMap;

#[derive(serde::Deserialize)]
struct TokenResponse {
    access_token: String,
    expires_in: u64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();

    let api_url = std::env::var("AGENTIDP_API_URL").unwrap_or_else(|_| "{{API_URL}}".to_string());
    let client_id = std::env::var("AGENTIDP_CLIENT_ID")?;
    let client_secret = std::env::var("AGENTIDP_CLIENT_SECRET")?;

    println!("Issuing token for agent {{AGENT_ID}} at {} ...", api_url);

    let client = reqwest::Client::new();
    let mut params = HashMap::new();
    params.insert("grant_type", "client_credentials");
    params.insert("client_id", &client_id);
    params.insert("client_secret", &client_secret);
    params.insert("scope", "agents:read");

    let response = client
        .post(format!("{}/api/v1/token", api_url))
        .form(&params)
        .send()
        .await?;

    if !response.status().is_success() {
        eprintln!("Token issuance failed: HTTP {}", response.status());
        std::process::exit(1);
    }

    let token: TokenResponse = response.json().await?;
    println!("✓ Token issued successfully!");
    println!("  Expires in: {}s", token.expires_in);
    let truncated = &token.access_token[..token.access_token.len().min(20)];
    println!("  Token (first 20 chars): {}...", truncated);

    Ok(())
}
