use anyhow::Result;
use meridian::llms::{
    anthropic::{
        messages::{AnthropicMessage, AnthropicMessageContent},
        AnthropicClient,
    },
    LLMProvider, StructuredLLMProvider,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::common::utils::{can_run_anthropic_test, setup_test_env, PromptFixture};

#[test]
fn test_anthropic_basic_completion() -> Result<()> {
    setup_test_env()?;

    // Skip test if Anthropic credentials aren't available
    if !can_run_anthropic_test() {
        return Ok(());
    }

    let anthropic_user_messages = PromptFixture::anthropic_user_messages();

    let anthropic_client = AnthropicClient::new();

    for message in anthropic_user_messages {
        let completion = anthropic_client.get_completion(vec![message])?;
        assert!(!completion.is_empty());
    }

    Ok(())
}

#[test]
fn test_anthropic_structured_response() -> Result<()> {
    setup_test_env()?;

    if !can_run_anthropic_test() {
        return Ok(());
    }

    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
    struct Step {
        explanation: String,
        output: String,
    }

    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
    struct MathResponse {
        steps: Vec<Step>,
        final_answer: String,
    }

    let anthropic_client = AnthropicClient::new();
    let messages = vec![
        AnthropicMessage::User {
            content: vec![AnthropicMessageContent::Text {
                text: "You are a helpful math tutor.".to_string(),
            }],
            tool_use_id: None,
        },
        AnthropicMessage::User {
            content: vec![AnthropicMessageContent::Text {
                text: "solve 8x + 31 = 2".to_string(),
            }],
            tool_use_id: None,
        },
    ];

    let response: MathResponse =
        anthropic_client.get_structured_response::<MathResponse>(messages)?;

    // Validate the response
    assert!(!response.steps.is_empty(), "Should have at least one step");
    assert!(
        !response.final_answer.is_empty(),
        "Should have a final answer"
    );

    // Print the response for debugging
    println!("Structured Response: {:#?}", response);

    Ok(())
}
