#[path = "../config.rs"]
mod config;
#[path = "../error.rs"]
mod error;
#[path = "../transport.rs"]
mod transport;
#[path = "../av_client.rs"]
mod av_client;

use av_client::AvClient;
use tokio;
use tracing::{info, error};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    let api_key = "PUOO7UPTNXN325NN";
    let base_url = "https://mcp.alphavantage.co/mcp";
    let url = format!("{}?apikey={}", base_url, api_key);

    info!("Connecting to: {}", url);

    let client = AvClient::connect(&url).await
        .map_err(|e| anyhow::anyhow!("Connect failed: {:?}", e))?;
    
    info!("Connected! Listing tools...");
    
    let tools = client.list_tools().await
        .map_err(|e| anyhow::anyhow!("List tools failed: {:?}", e))?;
        
    info!("Found {} tools:", tools.len());
    for tool in &tools {
        if tool.name == "GLOBAL_QUOTE" || tool.name == "COMPANY_OVERVIEW" {
            info!("Tool: {}", tool.name);
            info!("Schema: {:?}", tool.input_schema);
        }
    }

    // Test calling a tool
    let symbol = "600519.SS"; 
    let params = vec![("symbol", symbol), ("datatype", "json")];
    
    info!("Testing GLOBAL_QUOTE for {} (json)...", symbol);
    match client.query("GLOBAL_QUOTE", &params).await {
        Ok(v) => info!("GLOBAL_QUOTE result: {:?}", v),
        Err(e) => error!("GLOBAL_QUOTE failed: {:?}", e),
    }

    let params_simple = vec![("symbol", symbol)];
    info!("Testing INCOME_STATEMENT for {}...", symbol);
    match client.query("INCOME_STATEMENT", &params_simple).await {
        Ok(v) => info!("INCOME_STATEMENT result: {:?}", v),
        Err(e) => error!("INCOME_STATEMENT failed: {:?}", e),
    }

    Ok(())
}

