use anyhow::Result;
use std::io::{self, Write};

pub fn confirm_action(message: &str) -> Result<bool> {
    print!("{} (yes/no): ", message);
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    Ok(input.trim().to_lowercase() == "yes")
}

pub fn get_master_key() -> Result<String> {
    if let Ok(key) = std::env::var("DOQIUM_MASTER_KEY") {
        if !key.is_empty() {
            println!("Using master key from DOQIUM_MASTER_KEY environment variable");
            return Ok(key);
        }
    }

    let key = rpassword::prompt_password("Enter master key: ")?;
    Ok(key)
}

pub fn extract_title_from_content(content: &str) -> String {
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            let title = trimmed.trim_start_matches('#').trim();
            if !title.is_empty() {
                return title.to_string();
            }
        } else if !trimmed.is_empty() {
            return trimmed.to_string();
        }
    }

    content
        .lines()
        .next()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "Untitled".to_string())
}

pub fn sluggify(title: &str) -> String {
    let cleaned: String = title
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { ' ' })
        .collect();

    cleaned
        .to_lowercase()
        .split_whitespace()
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

pub fn parse_markdown_frontmatter(content: &str) -> Result<(serde_json::Value, String)> {
    if !content.starts_with("---\n") {
        return Ok((serde_json::json!({}), content.to_string()));
    }

    let rest = &content[4..];
    let end_pos = rest
        .find("\n---\n")
        .ok_or_else(|| anyhow::anyhow!("Could not find end of YAML frontmatter"))?;

    let frontmatter_str = &rest[..end_pos];
    let markdown_content = &rest[end_pos + 5..];

    let frontmatter: serde_json::Value = serde_yaml::from_str(frontmatter_str)
        .map_err(|e| anyhow::anyhow!("Failed to parse YAML frontmatter: {}", e))?;

    Ok((frontmatter, markdown_content.to_string()))
}

pub fn set_file_timestamps(
    file_path: &std::path::Path,
    created: &str,
    modified: &str,
) -> Result<()> {
    use std::time::SystemTime;

    let modified_dt = chrono::DateTime::parse_from_rfc3339(modified)
        .map_err(|e| anyhow::anyhow!("Failed to parse modified date: {}", e))?;

    let modified_time: SystemTime = modified_dt.into();

    #[cfg(unix)]
    {
        let created_dt = chrono::DateTime::parse_from_rfc3339(created)
            .map_err(|e| anyhow::anyhow!("Failed to parse created date: {}", e))?;
        let created_time: SystemTime = created_dt.into();

        filetime::set_file_times(
            file_path,
            filetime::FileTime::from_system_time(created_time),
            filetime::FileTime::from_system_time(modified_time),
        )?;
    }

    #[cfg(not(unix))]
    {
        filetime::set_file_mtime(
            file_path,
            filetime::FileTime::from_system_time(modified_time),
        )?;
    }

    Ok(())
}
