#!/usr/bin/env zsh
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

# Ensure essential environment variables are set
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
# export HERMES_TUI="${HERMES_TUI:-1}"
export ZDOTDIR="${ZDOTDIR:-$XDG_CONFIG_HOME/zsh}"
export ZSH_CACHE="${ZSH_CACHE:-$XDG_CACHE_HOME/zsh}"
# Keep antidote repos out of ~/Library/Caches so cleaners (mole) don't nuke plugins.
export ANTIDOTE_HOME="${ANTIDOTE_HOME:-$XDG_DATA_HOME/antidote}"

# Helper functions
function _source {
  [[ -f "$1" ]] && source "$1"
}

function _cache {
  local cache_dir="$XDG_CACHE_HOME/zsh"
  local cache_file="$cache_dir/$1.zsh"
  
  if [[ ! -f "$cache_file" ]] || [[ "$commands[$1]" -nt "$cache_file" ]]; then
    mkdir -p "$cache_dir"
    "$@" > "$cache_file"
  fi
  source "$cache_file"
}

# Source configuration
source $ZDOTDIR/config.zsh

# Load plugins via antidote's static file
# Fast path: source pre-bundled plugins from cache.
# Self-heal: if cache exists but plugin repos were purged, fall back to antidote.
ANTIDOTE_STATIC_FILE="$ZSH_CACHE/.zsh_plugins.zsh"

function _load_antidote {
  local antidote_cache_file="$ZSH_CACHE/antidote_path"
  local antidote_path=""

  if [[ -f "$antidote_cache_file" ]]; then
    antidote_path="$(cat "$antidote_cache_file")"
  else
    for antidote_file in /nix/store/*antidote*/share/antidote/antidote.zsh; do
      if [[ -f "$antidote_file" ]]; then
        antidote_path="$antidote_file"
        mkdir -p "${antidote_cache_file:h}"
        echo "$antidote_path" > "$antidote_cache_file"
        break
      fi
    done
  fi

  [[ -f "$antidote_path" ]] || return 1
  source "$antidote_path"
}

function _antidote_static_is_healthy {
  [[ -f "$ANTIDOTE_STATIC_FILE" ]] || return 1
  [[ "$ZDOTDIR/.zsh_plugins.txt" -nt "$ANTIDOTE_STATIC_FILE" ]] && return 1

  local expected_antidote_home="${ANTIDOTE_HOME/#\~/$HOME}"
  local line source_path
  while IFS= read -r line; do
    [[ "$line" == source\ \"* ]] || continue
    source_path="${line#source \"}"
    source_path="${source_path%%\"*}"
    source_path="${source_path//\$HOME/$HOME}"
    [[ -f "$source_path" ]] || return 1

    # Force re-bundle if static file points to old antidote home.
    if [[ "$source_path" == "$HOME/Library/Caches/antidote/"* || "$source_path" == "$HOME/.local/share/antidote/"* ]]; then
      [[ "$source_path" == "$expected_antidote_home/"* ]] || return 1
    fi
  done < "$ANTIDOTE_STATIC_FILE"

  return 0
}

if _antidote_static_is_healthy; then
  source "$ANTIDOTE_STATIC_FILE"
else
  _load_antidote && antidote load "$ZDOTDIR/.zsh_plugins.txt"
  if (( $+functions[antidote] )); then
    mkdir -p "$ZSH_CACHE"
    antidote bundle < "$ZDOTDIR/.zsh_plugins.txt" >| "$ANTIDOTE_STATIC_FILE"
  fi
fi

# P10k is loaded by antidote from .zsh_plugins.txt
# Load p10k config after antidote has sourced the theme
[[ -f $ZDOTDIR/.p10k.zsh ]] && source $ZDOTDIR/.p10k.zsh

## Bootstrap interactive sessions
if [[ $TERM != dumb ]]; then
  # nix-darwin handles compinit via enableGlobalCompInit = true
  # so we don't need to manually initialize it here
  
  # Add custom completions directory before sourcing other configs
  fpath=($ZDOTDIR/completions $fpath)

  # JJ completion setup - choose one method:
  # Option 1: Fast static completion (current, ~6ms)
  # (already loaded via fpath/_jj_fast)

  # Option 2: Official dynamic completion (~9ms, more features)
  # Uncomment to use dynamic completion instead of static:
  # eval "$(COMPLETE=zsh jj)" 2>/dev/null

  source $ZDOTDIR/keybinds.zsh
  source $ZDOTDIR/completion.zsh

  # Auto-generated by nixos
  _source $ZDOTDIR/extra.zshrc
  # tmux-smart-name exports TMUX_WINDOW_NAME_SCRIPT; this hook refreshes
  # window/title metadata on chpwd when the shell is running inside tmux.
  _source $ZDOTDIR/tmux-hooks.zsh
  # If you have host-local configuration, put it here
  _source $ZDOTDIR/local.zshrc

  # P10k config already loaded above when P10k theme was loaded
  # [[ -f $ZDOTDIR/.p10k.zsh ]] && source $ZDOTDIR/.p10k.zsh

  # Initialize zoxide with caching (needed for aliases)
  if (( $+commands[zoxide] )); then
    _cache zoxide init zsh
  fi
  
  # Defer only autopair which is not immediately needed
  {
    # Initialize autopair (deferred - happens when plugins are fully loaded)
    if (( $+functions[autopair-init] )); then
      autopair-init
    fi
  } &!
fi


# Hermes Agent — ensure ~/.local/bin is on PATH
export PATH="$HOME/.local/bin:$PATH"
