#!/bin/bash

# Daily Check Trigger Script
# Called by Windows Task Scheduler or Startup script
# Creates flag file for terminal auto-spawn

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FLAG_FILE="$HOME/.daily_check_pending"
STATE_FILE="$SCRIPT_DIR/.state.json"
LOG_FILE="$SCRIPT_DIR/daily_check.log"

# Ensure jq is available (for JSON parsing)
if ! command -v jq &> /dev/null; then
    echo "$(date): ERROR - jq not installed. Install with: sudo apt install jq" >> "$LOG_FILE"
    exit 1
fi

# Read last check date from state
LAST_CHECK=$(jq -r '.last_check_date' "$STATE_FILE" 2>/dev/null || echo "null")
TODAY=$(date +%Y-%m-%d)
CURRENT_HOUR=$(date +%H)

# Determine period of day
if [ $CURRENT_HOUR -ge 5 ] && [ $CURRENT_HOUR -lt 12 ]; then
    PERIOD="morning"
elif [ $CURRENT_HOUR -ge 12 ] && [ $CURRENT_HOUR -lt 17 ]; then
    PERIOD="afternoon"
else
    PERIOD="evening"
fi

# Log trigger
echo "$(date): Trigger called ($PERIOD)" >> "$LOG_FILE"

# Check if already done today
if [ "$LAST_CHECK" == "$TODAY" ]; then
    echo "$(date): Daily check already done today. Skipping." >> "$LOG_FILE"
    exit 0
fi

# Create flag file with period information
echo "$PERIOD" > "$FLAG_FILE"
echo "$(date): Flag file created ($PERIOD)" >> "$LOG_FILE"

# If running in WSL terminal context, launch immediately
if [ -n "$WSL_DISTRO_NAME" ] && [ -n "$TERM" ]; then
    echo "$(date): WSL terminal detected. Launching Claude Code immediately..." >> "$LOG_FILE"
    sleep 1
    cd "$SCRIPT_DIR"
    claude "daily check"
    rm -f "$FLAG_FILE"
    echo "$(date): Claude Code launched, flag removed" >> "$LOG_FILE"
else
    echo "$(date): No active terminal. Flag file will trigger on next terminal open." >> "$LOG_FILE"
fi

exit 0
