haj 0.3.7

the beautiful, cross-distro package manager and tui.
use crate::ui;
use crossterm::style::Stylize;
use std::io::Write;
use std::time::Duration;

fn prompt_confirm_with_default(msg: &str, default_yes: bool) -> bool {
    print!("{} {} ", "?".magenta().bold(), msg.bold());
    let _ = std::io::stdout().flush();

    if crossterm::terminal::enable_raw_mode().is_ok() {
        let mut result = false;
        loop {
            match crossterm::event::read() {
                Ok(crossterm::event::Event::Key(key)) => {
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL)
                        && key.code == crossterm::event::KeyCode::Char('c')
                    {
                        result = false;
                        break;
                    }
                    match key.code {
                        crossterm::event::KeyCode::Char('y' | 'Y') => {
                            result = true;
                            break;
                        }
                        crossterm::event::KeyCode::Char('n' | 'N') => {
                            result = false;
                            break;
                        }
                        crossterm::event::KeyCode::Enter => {
                            result = default_yes;
                            break;
                        }
                        _ => continue,
                    }
                }
                Ok(_) => continue,
                Err(_) => break,
            }
        }
        let _ = crossterm::terminal::disable_raw_mode();
        println!("{}", if result { "Y" } else { "n" });
        result
    } else {
        let mut input = String::new();
        let bytes = std::io::stdin().read_line(&mut input).unwrap_or(0);
        parse_confirm_fallback(bytes, &input, default_yes)
    }
}

pub fn prompt_confirm(msg: &str) -> bool {
    prompt_confirm_with_default(msg, true)
}

pub fn prompt_confirm_default_no(msg: &str) -> bool {
    prompt_confirm_with_default(msg, false)
}

fn parse_confirm_fallback(bytes_read: usize, line: &str, default_yes: bool) -> bool {
    if bytes_read == 0 {
        return false;
    }
    let input = line.trim().to_lowercase();
    if input.is_empty() {
        default_yes
    } else {
        input == "y"
    }
}

fn parse_install_choice_fallback(bytes_read: usize, line: &str) -> InstallChoice {
    if bytes_read == 0 {
        return InstallChoice::No;
    }
    let input = line.trim().to_lowercase();
    if input == "v" {
        InstallChoice::View
    } else if input.is_empty() || input == "y" {
        InstallChoice::Yes
    } else {
        InstallChoice::No
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallChoice {
    Yes,
    No,
    View,
}

pub fn prompt_install(msg: &str) -> InstallChoice {
    print!("{} {} ", "?".magenta().bold(), msg.bold());
    let _ = std::io::stdout().flush();

    if crossterm::terminal::enable_raw_mode().is_ok() {
        let mut result = InstallChoice::No;
        loop {
            match crossterm::event::read() {
                Ok(crossterm::event::Event::Key(key)) => {
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL)
                        && key.code == crossterm::event::KeyCode::Char('c')
                    {
                        result = InstallChoice::No;
                        break;
                    }
                    match key.code {
                        crossterm::event::KeyCode::Char('y' | 'Y')
                        | crossterm::event::KeyCode::Enter => {
                            result = InstallChoice::Yes;
                            break;
                        }
                        crossterm::event::KeyCode::Char('n' | 'N') => {
                            result = InstallChoice::No;
                            break;
                        }
                        crossterm::event::KeyCode::Char('v' | 'V') => {
                            result = InstallChoice::View;
                            break;
                        }
                        _ => continue,
                    }
                }
                Ok(_) => continue,
                Err(_) => break,
            }
        }
        let _ = crossterm::terminal::disable_raw_mode();
        let display_str = match result {
            InstallChoice::Yes => "Y",
            InstallChoice::No => "n",
            InstallChoice::View => "v",
        };
        println!("{display_str}");
        result
    } else {
        let mut input = String::new();
        let bytes = std::io::stdin().read_line(&mut input).unwrap_or(0);
        parse_install_choice_fallback(bytes, &input)
    }
}

fn extract_xml_tag<'a>(xml: &'a str, tag: &str) -> Option<&'a str> {
    let open = format!("<{tag}>");
    let close = format!("</{tag}>");
    let start = xml.find(&open)? + open.len();
    let rest = &xml[start..];
    let end = rest.find(&close)?;
    Some(rest[..end].trim())
}

pub async fn display_arch_news() {
    let spinner = ui::spinner("checking arch linux news...");
    let url = "https://archlinux.org/feeds/news/";

    let Ok(client) = reqwest::Client::builder()
        .timeout(Duration::from_secs(5))
        .build()
    else {
        spinner.finish_and_clear();
        return;
    };

    if let Ok(response) = client.get(url).send().await
        && let Ok(xml) = response.text().await
    {
        spinner.finish_and_clear();

        if let Some(item_start) = xml.find("<item>") {
            let item_str = &xml[item_start..];
            if let (Some(title), Some(date_str)) = (
                extract_xml_tag(item_str, "title"),
                extract_xml_tag(item_str, "pubDate"),
            ) && let Ok(pub_date) = chrono::DateTime::parse_from_rfc2822(date_str)
            {
                let now = chrono::Utc::now();
                if now
                    .signed_duration_since(pub_date.with_timezone(&chrono::Utc))
                    .num_days()
                    <= 7
                {
                    println!(
                        "\n{} {}\n  {} {}\n  {}\n",
                        "!!!".red().bold(),
                        "action required: recent arch linux news".red().bold(),
                        "headline:".dim(),
                        title.yellow().bold(),
                        "haj requests you to read the news before upgrading.".dim()
                    );
                }
            }
        }
    } else {
        spinner.finish_and_clear();
    }
}

pub fn handle_conflicts_ui<F>(
    conflicts: &[crate::backend::traits::ConflictInfo],
    dry_run: bool,
    noconfirm: bool,
    mut prompter: F,
) -> Result<bool, &'static str>
where
    F: FnMut(&str) -> bool,
{
    if conflicts.is_empty() {
        return Ok(false);
    }
    for conflict in conflicts {
        println!("\n{} package conflict detected\n", "✗".red());
        println!("  installing: {}", conflict.incoming_pkg.clone().bold());
        println!(
            "  conflicts with installed package: {}",
            conflict.installed_pkg.clone().bold()
        );
        if let Some(constraint) = &conflict.constraint {
            println!("  constraint: {}", constraint.clone().yellow());
        }
        println!("\n  only one of these packages can be installed.\n");

        if dry_run {
            println!(
                "{} would replace '{}' with '{}'",
                "[dry run]".bold().yellow(),
                conflict.installed_pkg,
                conflict.incoming_pkg
            );
        } else if noconfirm {
            return Err(
                "conflicting packages detected and --noconfirm used without explicit authorization. aborting.",
            );
        } else {
            let prompt = format!(
                "replace installed package '{}' with '{}'? [y/N]",
                conflict.installed_pkg, conflict.incoming_pkg
            );
            if !prompter(&prompt) {
                return Err("aborted: no changes were made.");
            }
        }
    }
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_eof_stdin_defaults_to_abort() {
        assert!(!parse_confirm_fallback(0, "", true));
        assert!(parse_confirm_fallback(1, "\n", true));
        assert!(!parse_confirm_fallback(1, "\n", false));
        assert!(parse_confirm_fallback(2, "y\n", false));
        assert!(!parse_confirm_fallback(2, "n\n", true));

        assert_eq!(parse_install_choice_fallback(0, ""), InstallChoice::No);
        assert_eq!(parse_install_choice_fallback(1, "\n"), InstallChoice::Yes);
        assert_eq!(parse_install_choice_fallback(2, "v\n"), InstallChoice::View);
        assert_eq!(parse_install_choice_fallback(2, "n\n"), InstallChoice::No);
    }

    #[test]
    fn test_extract_xml_tag_handles_reversed_tags() {
        assert_eq!(
            extract_xml_tag("</title><title>ok</title>", "title"),
            Some("ok")
        );
        assert_eq!(extract_xml_tag("</title><title>unclosed", "title"), None);
    }
}