use regex::Regex;
use std::collections::HashMap;

pub fn parse_sermon_details(text: &str) -> HashMap<String, String> {
    let mut details = HashMap::new();
    
    // Handle different input formats
    let lines: Vec<&str> = text.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();
    
    // Check for "Opening Song:", "Scripture:", "Sermon:" format
    for line in &lines {
        if line.starts_with("Opening Song:") {
            details.insert("opening_song".to_string(), line.replace("Opening Song:", "").trim().to_string());
        } else if line.starts_with("Scripture:") {
            details.insert("scripture_reading".to_string(), line.replace("Scripture:", "").trim().to_string());
        } else if line.starts_with("Sermon:") {
            details.insert("sermon_title".to_string(), line.replace("Sermon:", "").trim().to_string());
        } else if line.starts_with("Closing Song:") {
            details.insert("closing_song".to_string(), line.replace("Closing Song:", "").trim().to_string());
        } else if line.starts_with("Call to worship:") {
            details.insert("responsive_reading".to_string(), line.replace("Call to worship:", "").trim().to_string());
        }
    }
    
    // If we found data in the above format, return early
    if !details.is_empty() {
        return details;
    }
    
    // Try simple line-by-line parsing if no structured labels found
    if !text.contains("Sermon Title:") && !text.contains("Scripture Reading:") && lines.len() >= 3 {
        // Simple format: line 1 = speaker, line 2 = title, line 3 = scripture, etc.
        if lines.len() > 1 {
            details.insert("sermon_title".to_string(), lines[1].to_string());
        }
        if lines.len() > 2 {
            details.insert("scripture_reading".to_string(), lines[2].to_string());
        }
        if lines.len() > 3 && lines[3].starts_with("Opening:") {
            details.insert("opening_song".to_string(), lines[3].replace("Opening:", "").trim().to_string());
        }
        if lines.len() > 4 && lines[4].starts_with("Closing:") {
            details.insert("closing_song".to_string(), lines[4].replace("Closing:", "").trim().to_string());
        }
        if lines.len() > 5 && lines[5].starts_with("Responsive Reading:") {
            details.insert("responsive_reading".to_string(), lines[5].replace("Responsive Reading:", "").trim().to_string());
        }
        return details;
    }
    
    if text.contains("Sermon Title:") {
        let title_regex = Regex::new(r#"Sermon Title:\s*["\'""]([^"\'""]+)["\'""]"#).unwrap();
        if let Some(captures) = title_regex.captures(text) {
            details.insert("sermon_title".to_string(), captures.get(1).unwrap().as_str().trim().to_string());
        } else {
            let title_regex_no_quotes = Regex::new(r"Sermon Title:\s*([^\n\r]+)").unwrap();
            if let Some(captures) = title_regex_no_quotes.captures(text) {
                let title = captures.get(1).unwrap().as_str()
                    .trim()
                    .trim_matches('"')
                    .trim_matches('"')
                    .trim_matches('"')
                    .to_string();
                details.insert("sermon_title".to_string(), title);
            }
        }
    }
    
    if text.contains("Scripture Reading:") {
        let scripture_regex = Regex::new(r"Scripture Reading:\s*([^\n\r]+)").unwrap();
        if let Some(captures) = scripture_regex.captures(text) {
            details.insert("scripture_reading".to_string(), captures.get(1).unwrap().as_str().trim().to_string());
        }
    }
    
    if text.contains("Opening:") {
        let opening_regex = Regex::new(r"Opening:\s*([^\n\r]+)").unwrap();
        if let Some(captures) = opening_regex.captures(text) {
            let song = captures.get(1).unwrap().as_str().trim();
            let formatted_song = if song.contains(" - ") {
                let parts: Vec<&str> = song.splitn(2, " - ").collect();
                format!("#{} \"{}\"", parts[0].trim(), parts[1].trim())
            } else {
                song.to_string()
            };
            details.insert("opening_song".to_string(), formatted_song);
        }
    }
    
    if text.contains("Closing:") {
        let closing_regex = Regex::new(r"Closing:\s*([^\n\r]+)").unwrap();
        if let Some(captures) = closing_regex.captures(text) {
            let song = captures.get(1).unwrap().as_str().trim();
            let formatted_song = if song.contains(" - ") {
                let parts: Vec<&str> = song.splitn(2, " - ").collect();
                format!("#{} \"{}\"", parts[0].trim(), parts[1].trim())
            } else {
                song.to_string()
            };
            details.insert("closing_song".to_string(), formatted_song);
        }
    }
    
    if text.contains("Responsive Reading:") {
        let responsive_regex = Regex::new(r"Responsive Reading:\s*([^\n\r]+)").unwrap();
        if let Some(captures) = responsive_regex.captures(text) {
            let reading = captures.get(1).unwrap().as_str().trim();
            let formatted_reading = if reading.contains(" - ") {
                let parts: Vec<&str> = reading.splitn(2, " - ").collect();
                format!("Hymnal {} \"{}\"", parts[0].trim(), parts[1].trim())
            } else {
                reading.to_string()
            };
            details.insert("responsive_reading".to_string(), formatted_reading);
        }
    }
    
    details
}