use crate::agent::artifact::{ArtifactEntry, ArtifactError, ArtifactKind, ArtifactMetadata};
use crate::state::AppState;

#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactKindRequest {
    pub kind: String,
}

#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactLoadRequest {
    pub kind: String,
    pub name: String,
}

fn parse_kind(raw: &str) -> Result<ArtifactKind, String> {
    match raw.to_ascii_lowercase().as_str() {
        "note" => Ok(ArtifactKind::Note),
        "report" => Ok(ArtifactKind::Report),
        "export" => Ok(ArtifactKind::Export),
        other => Err(format!(
            "unknown artifact kind '{}'. Use note, report, or export.",
            other
        )),
    }
}

#[tauri::command]
pub async fn list_artifacts(
    state: tauri::State<'_, AppState>,
    request: ArtifactKindRequest,
) -> Result<Vec<ArtifactMetadata>, String> {
    let kind = parse_kind(&request.kind)?;
    state
        .artifact_store
        .list(kind)
        .map_err(|error: ArtifactError| error.to_string())
}

#[tauri::command]
pub async fn load_artifact(
    state: tauri::State<'_, AppState>,
    request: ArtifactLoadRequest,
) -> Result<ArtifactEntry, String> {
    let kind = parse_kind(&request.kind)?;
    state
        .artifact_store
        .load(kind, &request.name)
        .map_err(|error: ArtifactError| error.to_string())
}

#[tauri::command]
pub async fn delete_artifact(
    state: tauri::State<'_, AppState>,
    request: ArtifactLoadRequest,
) -> Result<(), String> {
    let kind = parse_kind(&request.kind)?;
    state
        .artifact_store
        .delete(kind, &request.name)
        .map_err(|error: ArtifactError| error.to_string())
}
