#!/usr/bin/env bash
# Timmy's Morrowind HUD — live view of what I see and do
# Run in a tmux pane: watch -n 3 -t -c bash ~/.timmy/morrowind/hud.sh

B='\033[1m'; D='\033[2m'; R='\033[0m'
G='\033[32m'; Y='\033[33m'; C='\033[36m'; M='\033[35m'; RD='\033[31m'

echo ""
echo -e "  ${B}${M}⚡ TIMMY — MORROWIND${R}                    ${D}$(date '+%H:%M:%S')${R}"
echo -e "  ${D}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${R}"

# Game status
PID=$(pgrep openmw 2>/dev/null | head -1)
if [ -n "$PID" ]; then
    echo -e "  ${G}●${R} OpenMW running (PID $PID)"
else
    echo -e "  ${RD}○${R} OpenMW not running"
fi

# Last action
echo ""
echo -e "  ${B}LAST ACTION${R}"
[ -f /tmp/timmy_last_action.txt ] && head -3 /tmp/timmy_last_action.txt | sed 's/^/  /' || echo -e "  ${D}None${R}"

# Perception
echo ""
echo -e "  ${B}PERCEPTION${R}"
[ -f /tmp/timmy_perception.txt ] && cat /tmp/timmy_perception.txt | sed 's/^/  /' || echo -e "  ${D}Waiting...${R}"

# Log (filtered)
echo ""
echo -e "  ${B}LOG (recent)${R}"
LOG=~/Library/Preferences/openmw/openmw.log
if [ -f "$LOG" ]; then
    tail -40 "$LOG" 2>/dev/null | grep -E "Loading cell|Starting|AiTravel|AiEscort|Timmy|ALIVE|Walk|error|PERCEPTION" | tail -5 | while read line; do
        echo -e "  ${D}${line}${R}"
    done
fi

# Latest screenshot as sixel/kitty or just path
echo ""
echo -e "  ${B}SCREENSHOT${R}"
LATEST=$(ls -t /tmp/timmy_screen_*.png 2>/dev/null | head -1)
if [ -n "$LATEST" ]; then
    AGE=$(( $(date +%s) - $(stat -f %m "$LATEST") ))
    echo -e "  ${C}$(basename $LATEST)${R}  ${D}(${AGE}s ago)${R}"
    # Try iTerm2 inline image protocol
    if [ "$TERM_PROGRAM" = "iTerm.app" ] || [ -n "$ITERM_SESSION_ID" ]; then
        printf '\033]1337;File=inline=1;width=60;preserveAspectRatio=1:'
        base64 < "$LATEST" | tr -d '\n'
        printf '\a\n'
    else
        echo -e "  ${D}(open $LATEST to view)${R}"
    fi
else
    echo -e "  ${D}No screenshots yet${R}"
fi
