use super::run_command;
use anyhow::Result;
use std::fs;

/// Executes a command in a new screen session.
///
/// # Arguments
///
/// * `name` - The name of the screen session.
/// * `cmd` - The command to execute.
///
/// # Returns
///
/// * `Result<()>` - Ok if the command was executed successfully, otherwise an error.
pub fn new(name: &str, cmd: &str) -> Result<()> {
    let script_path = format!("/tmp/cmd_{}.sh", name);
    let mut script_content = String::new();

    if !cmd.starts_with("#!") {
        script_content.push_str("#!/bin/bash\n");
    }

    script_content.push_str("set -e\n");
    script_content.push_str(cmd);

    fs::write(&script_path, script_content)?;
    fs::set_permissions(
        &script_path,
        std::os::unix::fs::PermissionsExt::from_mode(0o755),
    )?;

    let screen_cmd = format!("screen -d -m -S {} {}", name, script_path);
    run_command(&screen_cmd)?;

    Ok(())
}

/// Kills a screen session.
///
/// # Arguments
///
/// * `name` - The name of the screen session to kill.
///
/// # Returns
///
/// * `Result<()>` - Ok if the session was killed successfully, otherwise an error.
pub fn kill(name: &str) -> Result<()> {
    let cmd = format!("screen -S {} -X quit", name);
    run_command(&cmd)?;
    std::thread::sleep(std::time::Duration::from_millis(500));
    Ok(())
}
