#!/bin/bash

STATE_FILE="$HOME/.cache/brightness_state"
TEMP_FILE="$HOME/.cache/bluelight_state"

# Get screen brightness level
echo "Enter screen brightness level (0-10, where 10 = 100%):"
read -r LEVEL

# Validate input
if ! [[ "$LEVEL" =~ ^[0-9]+$ ]] || [ "$LEVEL" -lt 0 ] || [ "$LEVEL" -gt 10 ]; then
  echo "Invalid input. Please enter a number between 0 and 10."
  exit 1
fi

# Convert to decimal (0-10 -> 0.0-1.0)
BRIGHTNESS=$(echo "scale=2; $LEVEL / 10" | bc)

# Ensure at least 0.1 to avoid complete darkness
if (($(echo "$BRIGHTNESS < 0.1" | bc -l))); then
  BRIGHTNESS=0.1
fi

# Ask about blue light filter
echo "Apply blue light filter? (y/n):"
read -r BLUELIGHT

if [[ "$BLUELIGHT" == "y" || "$BLUELIGHT" == "Y" ]]; then
  TEMP=3400
  FILTER_MSG="with blue light filter"
else
  TEMP=6500
  FILTER_MSG=""
fi

# Apply settings
pkill -9 gammastep
gammastep -O $TEMP -b "$BRIGHTNESS" &>/dev/null &

# Save state
echo "$BRIGHTNESS" >"$STATE_FILE"
echo "$TEMP" >"$TEMP_FILE"

echo "Screen brightness set to ${LEVEL}0% $FILTER_MSG"
notify-send "Brightness" "${LEVEL}0% $FILTER_MSG" -t 2000
