//! Implements the hidden `limb mark-cd`. Editor-to-shell cwd bridge.
//!
//! Writes a marker file at `${TMPDIR}/limb-pending-cd-$TMUX_PANE` that
//! the precmd hook emitted by [`crate::shell`] reads on the shell's next
//! prompt. This lets `:LimbPick` in nvim propagate its cd back to the
//! parent shell after the user quits nvim. Without a hacky send-keys.
//!
//! Outside tmux this is a no-op: without a pane identifier, the marker
//! would be ambiguous.

use std::fs;

use anyhow::{Context as _, Result};

use crate::cli::MarkCdArgs;

/// Runs `limb mark-cd`.
///
/// No-ops (returning `Ok(())`) when `$TMUX_PANE` is unset.
///
/// # Errors
///
/// Returns an error if the path cannot be canonicalised or the marker
/// file cannot be written.
pub fn run(args: &MarkCdArgs) -> Result<()> {
    let Some(pane) = std::env::var_os("TMUX_PANE") else {
        return Ok(());
    };
    let marker = std::env::temp_dir().join(format!("limb-pending-cd-{}", pane.to_string_lossy()));
    let resolved = args
        .path
        .canonicalize()
        .with_context(|| format!("cannot resolve path: {}", args.path.display()))?;
    fs::write(&marker, format!("{}\n", resolved.display()))
        .with_context(|| format!("failed to write marker: {}", marker.display()))?;
    Ok(())
}
