use std::path::PathBuf;

use anyhow::{anyhow, Context, Result};
use better_panic::Settings;
use directories::ProjectDirs;
use tracing::{error, level_filters::LevelFilter};
use tracing_appender::{
  non_blocking::WorkerGuard,
  rolling::{RollingFileAppender, Rotation},
};
use tracing_subscriber::{
  self, filter::EnvFilter, prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, Layer,
};

pub fn initialize_panic_handler() {
  std::panic::set_hook(Box::new(|panic_info| {
    if let Err(r) = crate::terminal::exit() {
      error!("Unable to exit Terminal: {r:?}");
    }

    Settings::auto().most_recent_first(false).lineno_suffix(true).create_panic_handler()(panic_info);
    std::process::exit(libc::EXIT_FAILURE);
  }));
}

pub fn get_data_dir() -> Result<PathBuf> {
  let directory = if let Ok(s) = std::env::var("SYSTEMCTL_TUI_DATA") {
    PathBuf::from(s)
  } else if let Some(proj_dirs) = ProjectDirs::from("com", "rgwood", "systemctl-tui") {
    proj_dirs.data_local_dir().to_path_buf()
  } else {
    return Err(anyhow!("Unable to find data directory for systemctl-tui"));
  };
  Ok(directory)
}

pub fn get_config_dir() -> Result<PathBuf> {
  let directory = if let Ok(s) = std::env::var("SYSTEMCTL_TUI_CONFIG") {
    PathBuf::from(s)
  } else if let Some(proj_dirs) = ProjectDirs::from("com", "rgwood", "systemctl-tui") {
    proj_dirs.config_local_dir().to_path_buf()
  } else {
    return Err(anyhow!("Unable to find config directory for systemctl-tui"));
  };
  Ok(directory)
}

pub fn initialize_logging(enable_file_logging: bool) -> Result<Option<WorkerGuard>> {
  let mut guard = None;

  let file_layer = if enable_file_logging {
    let directory = get_data_dir()?;
    std::fs::create_dir_all(directory.clone()).context(format!("{directory:?} could not be created"))?;

    // create a file appender that rolls daily
    let file_appender = RollingFileAppender::new(Rotation::DAILY, &directory, "systemctl-tui.log");

    // create a non-blocking writer
    let (non_blocking, g) = tracing_appender::non_blocking(file_appender);

    // We must return this guard to main.rs and keep it alive
    guard = Some(g);

    // Log initialization info only if we are actually logging
    tracing::info!(directory = %directory.display(), "Logging initialized");

    // create a layer for the file logger
    Some(
      tracing_subscriber::fmt::layer()
        .with_writer(non_blocking)
        .with_file(true)
        .with_line_number(true)
        .with_target(false)
        .with_ansi(false)
        .with_filter(EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy()),
    )
  } else {
    None
  };

  tui_logger::init_logger(tui_logger::LevelFilter::Debug)?;

  let tui_layer = tui_logger::TuiTracingSubscriberLayer
    .with_filter(EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy());

  tracing_subscriber::registry().with(file_layer).with(tui_layer).init();

  Ok(guard)
}

/// Similar to the `std::dbg!` macro, but generates `tracing` events rather
/// than printing to stdout.
///
/// By default, the verbosity level for the generated events is `DEBUG`, but
/// this can be customized.
#[macro_export]
macro_rules! trace_dbg {
    (target: $target:expr, level: $level:expr, $ex:expr) => {{
        match $ex {
            value => {
                tracing::event!(target: $target, $level, ?value, stringify!($ex));
                value
            }
        }
    }};
    (level: $level:expr, $ex:expr) => {
        trace_dbg!(target: module_path!(), level: $level, $ex)
    };
    (target: $target:expr, $ex:expr) => {
        trace_dbg!(target: $target, level: tracing::Level::DEBUG, $ex)
    };
    ($ex:expr) => {
        trace_dbg!(level: tracing::Level::DEBUG, $ex)
    };
}

/// Copy text to the system clipboard. Always emits OSC 52 (works over SSH and inside tmux), and
/// additionally pipes the text to a system clipboard utility if one is available, for terminals
/// that don't support OSC 52.
pub fn copy_to_clipboard(text: &str) {
  copy_to_clipboard_osc52(text);
  copy_to_clipboard_native(text);
}

/// Best-effort copy via a system clipboard utility (wl-copy/xclip/xsel/pbcopy). These tools fork
/// and keep serving the selection after we exit, which a write-and-drop native clipboard library
/// can't do on X11/Wayland. Failures are silent by design; OSC 52 is the primary mechanism, and
/// all output is redirected to null so nothing can scribble on the TUI.
fn copy_to_clipboard_native(text: &str) {
  use std::{
    io::Write,
    process::{Command, Stdio},
  };

  let candidates: &[&[&str]] = if cfg!(target_os = "macos") {
    &[&["pbcopy"]]
  } else if std::env::var_os("WAYLAND_DISPLAY").is_some() {
    &[&["wl-copy"], &["xclip", "-selection", "clipboard"], &["xsel", "--clipboard", "--input"]]
  } else if std::env::var_os("DISPLAY").is_some() {
    &[&["xclip", "-selection", "clipboard"], &["xsel", "--clipboard", "--input"]]
  } else {
    return; // no display server; OSC 52 is the only option (e.g. over SSH)
  };

  let text = text.to_owned();
  let candidates: Vec<Vec<String>> = candidates.iter().map(|c| c.iter().map(|s| s.to_string()).collect()).collect();
  // Write and reap in a background thread so a slow or missing utility can't stall the UI.
  std::thread::spawn(move || {
    for candidate in candidates {
      let spawned = Command::new(&candidate[0])
        .args(&candidate[1..])
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn();
      if let Ok(mut child) = spawned {
        if let Some(mut stdin) = child.stdin.take() {
          let _ = stdin.write_all(text.as_bytes());
        }
        let _ = child.wait();
        return;
      }
    }
  });
}

/// Copy text to the system clipboard using an OSC 52 escape sequence, written directly to the
/// TUI's output stream (stderr). This works over SSH and inside tmux (with `set-clipboard on`)
/// without needing any special passthrough wrapping.
fn copy_to_clipboard_osc52(text: &str) {
  use std::io::Write;

  use base64::{engine::general_purpose::STANDARD, Engine};

  let encoded = STANDARD.encode(text);
  let mut stderr = std::io::stderr();
  if let Err(e) = write!(stderr, "\x1b]52;c;{encoded}\x07") {
    error!("Failed to write OSC 52 clipboard sequence: {e}");
    return;
  }
  let _ = stderr.flush();
}

pub fn version() -> String {
  let author = clap::crate_authors!();

  let version = env!("CARGO_PKG_VERSION");

  let config_dir_path = get_config_dir().unwrap().display().to_string();
  let data_dir_path = get_data_dir().unwrap().display().to_string();

  format!(
    "\
{version}

Authors: {author}

Config directory: {config_dir_path}
Data directory: {data_dir_path}"
  )
}
