#!/usr/bin/env bash

# Copyright 2026 Joseph McGuire
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice, this permission notice and the words
#
# "For God so loved the world, as to give his only begotten Son; that whosoever
# believeth in him, may not perish, but may have life everlasting."
# 
# shall be included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

set -euo pipefail

# Hacked together with first draft by Gemini Flash Extended
# 2026-10-04

# Configuration
PRIMARY_LOCKER="${PRIMARY_LOCKER:-i3lock}"
STATE_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/emacs_daily_lock_date"
WORD_TARGET=250
IMAGE="/home/joey/Pictures/DSC_5696.png"

TODAY=$(date +%Y-%m-%d)
LAST_COMPLETED=$(cat "$STATE_FILE" 2>/dev/null || echo "")

# 1. IMMEDIATE AUTHENTICATION LOCK
if command -v "$PRIMARY_LOCKER" >/dev/null 2>&1; then
    "$PRIMARY_LOCKER" --nofork --image="$IMAGE" "$@";
else
    echo "Error: Primary locker '$PRIMARY_LOCKER' not found." >&2
    exit 1
fi

# 2. POST-UNLOCK DATE CHECK
if [[ "$LAST_COMPLETED" == "$TODAY" ]]; then
    exit 0
fi

# 3. OPTIONAL: TRAP FOCUS IN i3
# Enter a custom i3 mode to disable workspace switching hotkeys (if configured in i3)
if command -v i3-msg >/dev/null 2>&1; then
    i3-msg 'mode "writing_lock"' >/dev/null 2>&1 || true
fi

# Function to ensure i3 mode is restored on script exit
cleanup() {
    if command -v i3-msg >/dev/null 2>&1; then
        i3-msg 'mode "default"' >/dev/null 2>&1 || true
    fi
}
trap cleanup EXIT

# 4. INLINE ELISP CONFIG
ELISP_CONFIG=$(cat <<EOF
(let ((target-words $WORD_TARGET))

  ;; Predicate to verify word count requirement
  (defun daily-lock-goal-met-p ()
    (let ((words (count-words (point-min) (point-max))))
      (if (>= words target-words)
          t
        (message "Doomed to Write: %d/%d words typed (%d remaining)"
                 words target-words (- target-words words))
        nil)))

  ;; Register exit trap immediately before any prompts appear
  (add-hook 'kill-emacs-query-functions #'daily-lock-goal-met-p)

  ;; Initialize Org-Roam
  (require 'org-roam)
  (require 'org-roam-dailies)
  (org-roam-db-autosync-mode)

  ;; Loop template menu until a note is chosen (catches 'q' or C-g aborts)
  (let ((selected nil))
    (while (not selected)
      (condition-case nil
          (progn
            (call-interactively #'org-roam-dailies-goto-today)
            (setq selected t))
        (quit (message "Selection required to proceed."))
        (error (message "Selection required to proceed.")))))

  ;; Save and exit handler bound to C-c C-c
  (defun finish-daily-lock-session ()
    (interactive)
    (if (daily-lock-goal-met-p)
        (progn
          (save-buffer)
          (kill-emacs 0))))

  (define-key global-map (kbd "C-c C-c") 'finish-daily-lock-session)

  ;; Live Header Line Word Counter
  (defun update-lock-header ()
    (let* ((words (count-words (point-min) (point-max)))
           (remaining (max 0 (- target-words words))))
      (setq header-line-format
            (if (<= remaining 0)
                (propertize " [GOAL REACHED] Press C-c C-c to save and dismiss "
                            'face '(:background "dark green" :foreground "white" :weight bold))
              (format " Daily Org-Roam Goal: %d / %d words (%d remaining) | Window Locked "
                      words target-words remaining)))))

  (add-hook 'post-command-hook 'update-lock-header nil t)
  (update-lock-header))
EOF
)

# Launch Doom Emacs with full screen and eval script
if emacs --eval "$ELISP_CONFIG" -name d2w; then
    echo "$TODAY" > "$STATE_FILE"
fi

# Complementary i3 configuration to prevent workspace switching:
# in ~/.config/i3/config
#
# # Execute d2w
# exec --no-startup-id /home/joey/script/d2w/d2w.sh
#
# # Transfer lock to i3lock via d2w.sh
# exec --no-startup-id xss-lock --transfer-sleep-lock -- /home/joey/script/d2w/d2w.sh
# 
# # Mode that blocks workspace navigation while daily writing prompt is active
# mode "writing_lock" {
#     Add only emergency bindings. Blank code block doesn't seem to allow
#     invoking the mode.
# }
# 
# # Set Doomed to Write to fullscreen when the window is created
#  for_window [instance="d2w"] fullscreen enable
