//! GitHub Issue Formatter
//!
//! Transforms WebhookPayload into GitHub Issue API format.
//! Used for posting learning reports to a GitHub repository.

use kaiba::WebhookPayload;

/// Format a webhook payload as a GitHub Issue
///
/// Expected payload.data fields (for LearningCompleted event):
/// - rei_name: String
/// - queries_generated: Vec<String>
/// - searches_completed: usize
/// - memories_stored: usize
/// - errors: Vec<String>
pub fn format_as_github_issue(payload: &WebhookPayload) -> serde_json::Value {
    let rei_name = payload
        .data
        .get("rei_name")
        .and_then(|v| v.as_str())
        .unwrap_or("Unknown Rei");

    let queries: Vec<&str> = payload
        .data
        .get("queries_generated")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
        .unwrap_or_default();

    let searches_completed = payload
        .data
        .get("searches_completed")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    let memories_stored = payload
        .data
        .get("memories_stored")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);

    let errors: Vec<&str> = payload
        .data
        .get("errors")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
        .unwrap_or_default();

    let date = payload.timestamp.format("%Y-%m-%d").to_string();
    let time = payload.timestamp.format("%H:%M:%S UTC").to_string();

    // Build title
    let title = format!("[{}] Learning Report - {}", rei_name, date);

    // Build body
    let queries_section = if queries.is_empty() {
        "- (no queries)".to_string()
    } else {
        queries
            .iter()
            .map(|q| format!("- {}", q))
            .collect::<Vec<_>>()
            .join("\n")
    };

    let errors_section = if errors.is_empty() {
        "None".to_string()
    } else {
        errors
            .iter()
            .map(|e| format!("- {}", e))
            .collect::<Vec<_>>()
            .join("\n")
    };

    let body = format!(
        r#"## Learning Session Report

**Rei**: {}
**Date**: {} {}
**Event**: {}

### Queries Searched
{}

### Results
| Metric | Value |
|--------|-------|
| Searches Completed | {} |
| Memories Stored | {} |

### Errors
{}

---
*Auto-generated by Kaiba*"#,
        rei_name,
        date,
        time,
        payload.event,
        queries_section,
        searches_completed,
        memories_stored,
        errors_section
    );

    // GitHub Issue API format
    serde_json::json!({
        "title": title,
        "body": body,
        "labels": ["learning-report", "auto-generated"]
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use kaiba::WebhookEventType;
    use uuid::Uuid;

    #[test]
    fn test_format_learning_completed() {
        let payload = WebhookPayload::new(
            WebhookEventType::LearningCompleted,
            Uuid::new_v4(),
            serde_json::json!({
                "rei_name": "TestRei",
                "queries_generated": ["Rust async", "WebAssembly"],
                "searches_completed": 2,
                "memories_stored": 2,
                "errors": []
            }),
        );

        let result = format_as_github_issue(&payload);

        assert!(result.get("title").is_some());
        assert!(result.get("body").is_some());
        assert!(result.get("labels").is_some());

        let title = result["title"].as_str().unwrap();
        assert!(title.contains("TestRei"));
        assert!(title.contains("Learning Report"));
    }
}
