//! Agent Skills VS Code Format Export Examples
//!
//! This example demonstrates how to export skills in VS Code's SKILL.md format,
//! which is compatible with Claude Code and VS Code integration.

use claude_agent_sdk::skills::types::{SkillMetadata, SkillPackage, SkillResources};
use claude_agent_sdk::skills::vscode::{
    VsCodeExportConfig, VsCodeUtils, export_batch_to_vscode, export_to_vscode,
};
use std::path::PathBuf;
use uuid::Uuid;

fn create_skill(name: &str, description: &str, tags: Vec<&str>) -> SkillPackage {
    SkillPackage {
        metadata: SkillMetadata {
            id: Uuid::new_v4().to_string(),
            name: name.to_string(),
            description: description.to_string(),
            version: "1.0.0".to_string(),
            author: Some("Claude SDK Team".to_string()),
            dependencies: vec!["claude-agent-sdk-rs".to_string()],
            tags: tags.into_iter().map(String::from).collect(),
        },
        instructions: format!(
            "You are a {} assistant. Help users with {} related tasks.",
            name, name
        ),
        scripts: vec![
            "#!/bin/bash\necho 'Running {} script'".replace("{}", name),
            "fn main() {\n    println!(\"{} in Rust\");\n}".replace("{}", name),
        ],
        resources: {
            let mut res = SkillResources::default();
            res.folders.push(PathBuf::from(format!(
                "./resources/{}",
                name.to_lowercase().replace(" ", "-")
            )));
            res.tools.push(format!("{}-tool", name.to_lowercase()));
            res
        },
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize tracing
    // tracing_subscriber::fmt::init();

    println!("=== Agent Skills VS Code Export Demo ===\n");

    // Example 1: Name normalization
    println!("1. Name Normalization");
    println!("----------------------");
    let names = vec![
        "My Custom Skill",
        "Rust API Helper",
        "Test_API_123",
        "Data Science Tool",
    ];

    for name in names {
        let normalized = VsCodeUtils::normalize_name(name);
        println!("  \"{}\" -> \"{}\"", name, normalized);
    }
    println!();

    // Example 2: Name validation
    println!("2. Name Validation");
    println!("------------------");
    let long_name = "a".repeat(65);
    let test_names = vec![
        ("my-skill", true),
        ("MySkill", false),
        ("123-skill", false),
        ("my_skill", false),
        ("a", true),
        (long_name.as_str(), false),
    ];

    for (name, should_be_valid) in test_names {
        let result = VsCodeUtils::validate_name(name);
        let is_valid = result.is_ok();
        let status = if is_valid == should_be_valid {
            "✓"
        } else {
            "✗"
        };
        println!(
            "  {} \"{}\": valid={}, expected={}",
            status, name, is_valid, should_be_valid
        );
    }
    println!();

    // Example 3: Description validation
    println!("3. Description Validation");
    println!("------------------------");
    let long_desc = "x".repeat(201);
    let descriptions = vec!["A valid skill description", long_desc.as_str(), ""];

    for desc in descriptions {
        let result = VsCodeUtils::validate_description(desc);
        match result {
            Ok(()) => println!("  ✓ Valid: \"{}\"", desc),
            Err(e) => println!("  ✗ Invalid: {} (length: {})", e, desc.len()),
        }
    }
    println!();

    // Example 4: Export configuration
    println!("4. Export Configuration");
    println!("-----------------------");
    let config = VsCodeExportConfig::new()
        .with_dependencies(true)
        .with_resources(true)
        .with_examples(true)
        .with_footer("Generated by Claude Agent SDK Rust".to_string());

    println!("Include dependencies: {}", config.include_dependencies);
    println!("Include resources: {}", config.include_resources);
    println!("Include examples: {}", config.include_examples);
    println!("Footer: {:?}", config.footer);
    println!();

    // Example 5: Single skill export
    println!("5. Single Skill Export");
    println!("----------------------");
    let skill = create_skill(
        "Rust Developer",
        "Expert Rust programming assistant",
        vec!["rust", "programming", "development"],
    );

    let output_path = PathBuf::from("/tmp/rust-developer.md");
    match export_to_vscode(&skill, &output_path, &config) {
        Ok(()) => {
            println!("✓ Exported skill to: {:?}", output_path);
            // Read and display first few lines
            if let Ok(content) = std::fs::read_to_string(&output_path) {
                let lines: Vec<&str> = content.lines().take(15).collect();
                println!("\nPreview (first 15 lines):");
                for line in lines {
                    println!("  {}", line);
                }
                println!("  ...");
            }
        },
        Err(e) => println!("✗ Export failed: {}", e),
    }
    println!();

    // Example 6: Batch export
    println!("6. Batch Export to Directory");
    println!("----------------------------");
    let skills = vec![
        create_skill(
            "Python Expert",
            "Python programming help",
            vec!["python", "programming"],
        ),
        create_skill(
            "Web Developer",
            "Web development assistance",
            vec!["web", "javascript", "html"],
        ),
        create_skill(
            "Data Analyst",
            "Data analysis and visualization",
            vec!["data", "analysis"],
        ),
    ];

    let output_dir = PathBuf::from("/tmp/skills_export");
    match export_batch_to_vscode(&skills, &output_dir, &config) {
        Ok(exported) => {
            println!("✓ Exported {} skills to {:?}", exported.len(), output_dir);
            for path in exported {
                println!("  - {}", path);
            }
        },
        Err(e) => println!("✗ Batch export failed: {}", e),
    }
    println!();

    // Example 7: Minimal export config
    println!("7. Minimal Export Configuration");
    println!("-------------------------------");
    let minimal_config = VsCodeExportConfig::new()
        .with_dependencies(false)
        .with_resources(false)
        .with_examples(false);

    let skill = create_skill("Minimal Skill", "A minimal skill", vec!["test"]);
    let output_path = PathBuf::from("/tmp/minimal-skill.md");

    match export_to_vscode(&skill, &output_path, &minimal_config) {
        Ok(()) => {
            println!("✓ Exported minimal skill to: {:?}", output_path);
            if let Ok(content) = std::fs::read_to_string(&output_path) {
                let lines: Vec<&str> = content.lines().take(10).collect();
                println!("\nPreview (first 10 lines):");
                for line in lines {
                    println!("  {}", line);
                }
            }
        },
        Err(e) => println!("✗ Export failed: {}", e),
    }
    println!();

    // Example 8: Export with custom footer
    println!("8. Export with Custom Footer");
    println!("---------------------------");
    let custom_footer_config = VsCodeExportConfig::new().with_footer(
        "---
Copyright © 2025

This skill is part of the Claude Agent SDK Rust project.
For more information, visit: https://github.com/louloulin/claude-agent-sdk"
            .to_string(),
    );

    let skill = create_skill("Copyrighted Skill", "Skill with copyright", vec!["demo"]);
    let output_path = PathBuf::from("/tmp/copyrighted-skill.md");

    match export_to_vscode(&skill, &output_path, &custom_footer_config) {
        Ok(()) => {
            println!("✓ Exported skill with footer to: {:?}", output_path);
            if let Ok(content) = std::fs::read_to_string(&output_path) {
                let footer_start = content.find("---").unwrap_or(content.len());
                let footer = &content[footer_start..];
                println!("\nFooter section:");
                for line in footer.lines().take(10) {
                    println!("  {}", line);
                }
            }
        },
        Err(e) => println!("✗ Export failed: {}", e),
    }
    println!();

    // Example 9: Name normalization edge cases
    println!("9. Name Normalization Edge Cases");
    println!("--------------------------------");
    let edge_cases = vec![
        ("UPPERCASE", "uppercase"),
        ("Multiple   Spaces", "multiple-spaces"),
        ("special@#$%characters", "specialchars"),
        ("123starting-number", "starting-number"),
        ("_underscore", "underscore"),
        ("trailing-hyphen-", "trailing-hyphen"),
    ];

    for (input, expected) in edge_cases {
        let normalized = VsCodeUtils::normalize_name(input);
        let match_status = if normalized == expected { "✓" } else { "✗" };
        println!(
            "  {} \"{}\" -> \"{}\" (expected: \"{}\")",
            match_status, input, normalized, expected
        );
    }
    println!();

    // Example 10: Complete workflow
    println!("10. Complete Workflow: Create -> Validate -> Export");
    println!("-------------------------------------------------");

    // Create a production-ready skill
    let skill = SkillPackage {
        metadata: SkillMetadata {
            id: Uuid::new_v4().to_string(),
            name: "API Documentation Generator".to_string(),
            description: "Automatically generates comprehensive API documentation from code"
                .to_string(),
            version: "2.1.0".to_string(),
            author: Some("Documentation Team".to_string()),
            dependencies: vec!["rust-doc".to_string(), "markdown-parser".to_string()],
            tags: vec![
                "documentation".to_string(),
                "api".to_string(),
                "generator".to_string(),
            ],
        },
        instructions: r#"
Generate comprehensive API documentation following these guidelines:

1. **Structure**: Organize documentation logically with clear sections
2. **Examples**: Include usage examples for each API endpoint
3. **Types**: Document all input/output types
4. **Errors**: List possible error conditions
5. **Authentication**: Clearly mark authenticated endpoints
"#
        .to_string(),
        scripts: vec![
            "#!/bin/bash\n# Generate docs from Rust source code\ncargo doc --no-deps --open"
                .to_string(),
        ],
        resources: {
            let mut res = SkillResources::default();
            res.folders.push(PathBuf::from("./templates"));
            res.tools.push("rust-doc".to_string());
            res.tests.push("./tests/doc_tests.rs".to_string());
            res
        },
    };

    // Validate the name
    let normalized_name = VsCodeUtils::normalize_name(&skill.metadata.name);
    println!("Normalized name: {}", normalized_name);

    match VsCodeUtils::validate_name(&normalized_name) {
        Ok(()) => println!("✓ Name is valid"),
        Err(e) => println!("✗ Name validation failed: {}", e),
    }

    // Export
    let output_path = PathBuf::from("/tmp/api-doc-generator.md");
    let config = VsCodeExportConfig::default();

    match export_to_vscode(&skill, &output_path, &config) {
        Ok(()) => {
            println!("✓ Exported successfully to: {:?}", output_path);
            println!("\nFile structure:");
            println!("  - YAML frontmatter with name, description, version, author, tags");
            println!("  - Instructions section");
            println!("  - Scripts section with syntax highlighting");
            println!("  - Dependencies section");
            println!("  - Resources section (folders, tools, tests)");
            println!("  - Usage examples section");
        },
        Err(e) => println!("✗ Export failed: {}", e),
    }

    println!();
    println!("=== Demo Complete ===");
    println!();
    println!("Key Features:");
    println!("- Automatic name normalization to VS Code format");
    println!("- Comprehensive validation (name, description)");
    println!("- Flexible export configuration");
    println!("- Single and batch export support");
    println!("- Customizable footer");
    println!("- Proper YAML frontmatter structure");
    println!("- Syntax highlighting for scripts");
    println!("- Organized markdown output");

    Ok(())
}
