//! Simple integration test demonstrating the complete MDX → Nickel → Execution pipeline

use std::collections::HashMap;
use typedialog_ag_core::executor::AgentExecutor;
use typedialog_ag_core::nickel::NickelEvaluator;
use typedialog_ag_core::parser::MarkupParser;
use typedialog_ag_core::transpiler::NickelTranspiler;

#[tokio::test]
#[ignore] // Requires ANTHROPIC_API_KEY for real LLM execution
async fn test_complete_pipeline_with_llm() {
    // Read simple MDX file
    let mdx_content = std::fs::read_to_string("tests/fixtures/simple.agent.mdx")
        .expect("Failed to read simple.agent.mdx");

    println!("MDX Content:\n{}\n", mdx_content);

    // Step 1: Parse MDX to AST
    let parser = MarkupParser::new();
    let ast = parser.parse(&mdx_content).expect("Failed to parse MDX");
    println!("AST parsed successfully with {} nodes\n", ast.nodes.len());

    // Step 2: Transpile AST to Nickel
    let transpiler = NickelTranspiler::new();
    let nickel_code = transpiler
        .transpile(&ast)
        .expect("Failed to transpile to Nickel");
    println!("Generated Nickel code:\n{}\n", nickel_code);

    // Step 3: Evaluate Nickel to AgentDefinition
    let evaluator = NickelEvaluator::new();
    let mut agent_def = evaluator
        .evaluate(&nickel_code)
        .expect("Failed to evaluate Nickel");

    // Use real Claude model
    agent_def.config.llm = "claude-3-5-haiku-20241022".to_string();
    agent_def.config.max_tokens = 100;

    println!("AgentDefinition: {:#?}\n", agent_def);

    // Step 4: Execute agent with real LLM
    let executor = AgentExecutor::new();
    let mut inputs = HashMap::new();
    inputs.insert("name".to_string(), serde_json::json!("Alice"));

    let result = executor
        .execute(&agent_def, inputs)
        .await
        .expect("Failed to execute agent");
    println!("LLM Response:\n{}\n", result.output);

    // Verify execution completed successfully
    assert!(!result.output.is_empty());
    assert!(result.metadata.duration_ms.is_some());
    assert!(result.metadata.tokens.is_some());
    assert_eq!(
        result.metadata.model,
        Some("claude-3-5-haiku-20241022".to_string())
    );

    println!("✓ Complete pipeline with LLM test passed!");
    println!("Tokens used: {:?}", result.metadata.tokens);
}

#[test]
fn test_nickel_syntax() {
    // Verify transpiler generates valid Nickel syntax
    let mdx_content = r#"---
@agent {
  role: tester,
  llm: claude
}
---

Test content
"#;

    let parser = MarkupParser::new();
    let ast = parser.parse(mdx_content).expect("Failed to parse");

    let transpiler = NickelTranspiler::new();
    let nickel_code = transpiler.transpile(&ast).expect("Failed to transpile");

    // Verify Nickel type checking passes
    let evaluator = NickelEvaluator::new();
    evaluator.typecheck(&nickel_code).expect("Typecheck failed");

    println!("✓ Nickel syntax validation passed!");
}
