#!/usr/bin/env bash

module_description() {
  printf "Dotfiles - deploy configuration files to ~/.config\n"
}

module_required() { return 0; }
module_should_skip() { return 1; }

module_prereqs() {
  return 0
}

module_main() {
  log_section "Dotfile Deployment"

  local dotfiles_dir="$OMERON_PROJECT_DIR/dotfiles"
  local config_items=()
  local backup_dir

  if [[ -f "$OMERON_PROJECT_DIR/config/omeron.yaml" ]] && command -v python3 >/dev/null 2>&1; then
    log_info "Loading config items from omeron.yaml"
    config_items=()
    local raw_items
    raw_items="$(python3 -c "
import yaml
with open('$OMERON_PROJECT_DIR/config/omeron.yaml') as f:
    data = yaml.safe_load(f)
items = data.get('dotfiles', {}).get('items', [])
print(' '.join(items))
" 2>/dev/null)"

    if [[ -n "$raw_items" ]]; then
      read -ra config_items <<< "$raw_items"
    fi
  fi

  if ((${#config_items[@]} == 0)); then
    config_items=(hypr waybar wofi swaync kitty gtk-3.0 gtk-4.0 qt5ct qt6ct)
  fi

  if ! tui_confirm "Deploy dotfiles to ~/.config? (existing files will be backed up)"; then
    log_info "Dotfile deployment skipped by user"
    return 0
  fi

  backup_dir="$(backup_file "$HOME/.config/hypr" "$HOME/.dotfiles-backup/$(date +%Y%m%d-%H%M%S)")"
  backup_dir="$(dirname "$backup_dir" 2>/dev/null || printf '%s' "$HOME/.dotfiles-backup/$(date +%Y%m%d-%H%M%S)")"

  for item in "${config_items[@]}"; do
    local source="$dotfiles_dir/$item"
    local target="$HOME/.config/$item"

    if [[ ! -d "$source" ]] && [[ ! -f "$source" ]]; then
      log_warn "Source not found: $source"
      continue
    fi

    log_info "Deploying $item..."
    copy_path "$source" "$target"
  done

  if [[ -f "$dotfiles_dir/starship.toml" ]]; then
    copy_path "$dotfiles_dir/starship.toml" "$HOME/.config/starship.toml"
  fi

  local wallpaper_source="$dotfiles_dir/wallpapers"
  local wallpaper_target="$HOME/Bilder/Wallpaper"
  if [[ -d "$wallpaper_source" ]]; then
    copy_path "$wallpaper_source" "$wallpaper_target"
  fi

  chmod +x "$HOME/.config/hypr/Scripts/"*.sh 2>/dev/null || true
  chmod +x "$HOME/.config/hypr/Scripts/"*.py 2>/dev/null || true
  chmod +x "$HOME/.config/hypr/scripts/"*.sh 2>/dev/null || true
  chmod +x "$HOME/.config/waybar/scripts/"*.sh 2>/dev/null || true

  replace_home_paths "$HOME/.config/hypr" "/home/pascal"
  replace_home_paths "$HOME/.config/wofi" "/home/pascal"
  replace_home_paths "$HOME/.config/gtk-3.0" "/home/pascal"
  replace_home_paths "$HOME/.config/gtk-4.0" "/home/pascal"
  replace_home_paths "$HOME/.config/qt5ct" "/home/pascal"
  replace_home_paths "$HOME/.config/qt6ct" "/home/pascal"

  log_success "Dotfiles deployed (backup: $backup_dir)"
}
