//! Simple chat example: send a prompt to the LLM and print the response.
//!
//! # Setup
//!
//! Create a `.env` file in `peon-runtime/` (see `.env.example`):
//! ```text
//! PROVIDER=openai
//! MODEL=gpt-4o-mini
//! API_KEY=sk-...
//! ```
//!
//! # Run
//!
//! ```bash
//! cargo run -p peon-runtime --example simple_chat
//! cargo run -p peon-runtime --example simple_chat -- "Tell me a joke"
//! ```

use peon_runtime::providers::anthropic::AnthropicProvider;
use peon_runtime::providers::gemini::GeminiProvider;
use peon_runtime::providers::openai::OpenAiProvider;
use peon_runtime::{AgentLoop, CompletionProvider, RequestContext};

fn create_provider() -> Box<dyn CompletionProvider> {
    dotenvy::dotenv().ok();

    let provider = std::env::var("PROVIDER").unwrap_or_else(|_| "openai".into());
    let api_key = std::env::var("API_KEY").expect("API_KEY not set in .env");

    match provider.as_str() {
        "openai" => {
            let model = std::env::var("MODEL").unwrap_or_else(|_| "gpt-4o-mini".into());
            println!("Using OpenAI: {}", model);
            Box::new(OpenAiProvider::new(model, api_key))
        }
        "anthropic" => {
            let model =
                std::env::var("MODEL").unwrap_or_else(|_| "claude-sonnet-4-20250514".into());
            println!("Using Anthropic: {}", model);
            Box::new(AnthropicProvider::new(model, api_key))
        }
        "gemini" => {
            let model = std::env::var("MODEL").unwrap_or_else(|_| "gemini-2.5-flash".into());
            println!("Using Gemini: {}", model);
            Box::new(GeminiProvider::new(model, api_key))
        }
        "openrouter" => {
            let model = std::env::var("MODEL")
                .unwrap_or_else(|_| "anthropic/claude-sonnet-4-20250514".into());
            println!("Using OpenRouter: {}", model);
            Box::new(OpenAiProvider::openrouter(model, api_key))
        }
        other => panic!(
            "Unknown PROVIDER: '{}'. Supported: openai, anthropic, gemini, openrouter",
            other
        ),
    }
}

#[tokio::main]
async fn main() {
    env_logger::init();

    let provider = create_provider();

    let agent = AgentLoop::builder(provider)
        .system_prompt("You are a helpful assistant. Be concise.")
        .max_turns(1) // No tools, so 1 turn is enough
        .build();

    let ctx = RequestContext::new("example_user");

    let prompt = std::env::args()
        .nth(1)
        .unwrap_or_else(|| "What is the capital of France? Answer in one sentence.".into());

    println!("\n> {}\n", prompt);

    match agent.run(prompt.as_str(), &[], &ctx).await {
        Ok(response) => {
            println!("{}\n", response.output);
            if let Some(usage) = &response.usage.input_tokens {
                println!(
                    "Tokens: {} in / {} out",
                    usage,
                    response.usage.output_tokens.unwrap_or(0)
                );
            }
        }
        Err(e) => {
            eprintln!("Error: {}", e);
        }
    }
}
