use crate::{error::SemanticPenError, types::*, Result};
use reqwest::{Client, Response};
use serde_json::Value;
use std::time::Duration;
pub struct SemanticPenClient {
client: Client,
api_key: String,
config: ClientConfig,
}
impl SemanticPenClient {
pub fn new(api_key: String) -> Result<Self> {
Self::with_config(api_key, ClientConfig::default())
}
pub fn with_config(api_key: String, config: ClientConfig) -> Result<Self> {
if api_key.is_empty() {
return Err(SemanticPenError::config_error("API key cannot be empty"));
}
let client = Client::builder()
.timeout(Duration::from_secs(config.timeout_seconds))
.build()?;
Ok(Self {
client,
api_key,
config,
})
}
async fn make_request(&self, method: &str, endpoint: &str, body: Option<Value>) -> Result<Response> {
let url = format!("{}{}", self.config.base_url, endpoint);
if self.config.debug {
println!("🔗 {} {}", method, url);
if let Some(ref body) = body {
println!("📤 Request body: {}", serde_json::to_string_pretty(body)?);
}
}
let mut request = match method {
"GET" => self.client.get(&url),
"POST" => self.client.post(&url),
"PUT" => self.client.put(&url),
"DELETE" => self.client.delete(&url),
_ => return Err(SemanticPenError::config_error(format!("Unsupported HTTP method: {}", method))),
};
request = request.header("Authorization", format!("Bearer {}", self.api_key));
if let Some(body) = body {
request = request
.header("Content-Type", "application/json")
.json(&body);
}
let response = request.send().await?;
if self.config.debug {
println!("📥 Response status: {}", response.status());
}
Ok(response)
}
pub async fn generate_article(&self, target_keyword: &str, project_name: Option<&str>) -> Result<GenerateArticleResponse> {
let request = GenerateArticleRequest {
target_keyword: target_keyword.to_string(),
project_name: project_name.map(|s| s.to_string()),
};
let body = serde_json::to_value(&request)?;
let response = self.make_request("POST", "/api/articles", Some(body)).await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SemanticPenError::api_error(status, error_text));
}
let result: GenerateArticleResponse = response.json().await?;
if self.config.debug {
println!("✅ Article generation response: {:?}", result);
}
Ok(result)
}
pub async fn get_article(&self, article_id: &str) -> Result<Article> {
let endpoint = format!("/api/articles/{}", article_id);
let response = self.make_request("GET", &endpoint, None).await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SemanticPenError::api_error(status, error_text));
}
let article: Article = response.json().await?;
if self.config.debug {
println!("📄 Article status: {} ({}%)", article.status, article.progress);
}
Ok(article)
}
pub async fn wait_for_article(&self, article_id: &str, polling_config: Option<PollingConfig>) -> Result<Article> {
let config = polling_config.unwrap_or_default();
for attempt in 1..=config.max_attempts {
let article = self.get_article(article_id).await?;
if self.config.debug {
println!("⏳ Attempt {}/{}: {} ({}%)",
attempt, config.max_attempts, article.status, article.progress);
}
if article.is_finished() {
if self.config.debug {
println!("✅ Article completed successfully!");
}
return Ok(article);
}
if article.is_failed() {
let error_msg = article.error_message
.unwrap_or_else(|| "Article generation failed".to_string());
return Err(SemanticPenError::api_error(500, error_msg));
}
if attempt < config.max_attempts {
tokio::time::sleep(Duration::from_secs(config.interval_seconds)).await;
}
}
Err(SemanticPenError::timeout_error(
format!("Article did not complete within {} attempts", config.max_attempts)
))
}
pub async fn generate_article_and_wait(&self, target_keyword: &str, project_name: Option<&str>, polling_config: Option<PollingConfig>) -> Result<Article> {
let response = self.generate_article(target_keyword, project_name).await?;
let article_id = response.get_article_id()
.ok_or_else(|| SemanticPenError::api_error(500, "No article ID returned".to_string()))?;
self.wait_for_article(&article_id, polling_config).await
}
pub async fn generate_bulk_articles(&self, keywords: &[String], project_name: Option<&str>) -> Result<Vec<String>> {
let mut article_ids = Vec::new();
for keyword in keywords {
let response = self.generate_article(keyword, project_name).await?;
if let Some(article_id) = response.get_article_id() {
article_ids.push(article_id);
}
}
Ok(article_ids)
}
}