#!/bin/bash

# Log current draw for specified port to stdout

# Source hardware configuration reader and set paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "/usr/share/rpi-power-hat/scripts/hardware-reader.sh"
MEASUREMENTS_DIR="/var/lib/rpi-power-hat/measurements"

# Ensure measurements directory exists
mkdir -p "$MEASUREMENTS_DIR"

print_usage() {
	echo "Current draw logging script"
	echo "Usage: rpi-power-hat log-current <port> [duration] [-s]"
	echo
	echo "Arguments:"
	echo "  port      - B1, B2, T1, T2"
	echo "  duration  - optional, in seconds (default: run until Ctrl+C)"
	echo "  -s        - save to CSV file (default: console only) duration is required"
	echo
	echo "Polling interval: 10 ms (100 Hz)"
	echo "Output format (console): fixed-width columns with whitespace between fields"
	echo "  Header: 'Time(s)    Current(mA)'"
	echo "  Row:    <seconds>   <milliamps>"
	echo "Output format (CSV with -s): 'elapsed_time,current_reading'"
	echo
	echo "Examples:"
	echo "  rpi-power-hat log-current B1           # Log port B1 to console only"
	echo "  rpi-power-hat log-current B1 30        # Log port B1 for 30 seconds to console"
	echo "  rpi-power-hat log-current B1 30 -s     # Log port B1 for 30 seconds to console and CSV"
}


# Main logging function
log_current() {
    local port="$1"
    local duration="$2"
    local save_csv="$3"
    
    local hwmon_path=$(get_current_hwmon_path "$port")
    if [[ ! -f "$hwmon_path" ]]; then
        echo "Error: Hardware monitoring path not found: $hwmon_path" >&2
        echo "Please check if the port $port is correctly mapped" >&2
        return 1
    fi
    
    local output_file=""
    if [[ "$save_csv" == "true" ]]; then
        local timestamp=$(date +%Y%m%d_%H%M%S)
        output_file="$MEASUREMENTS_DIR/current_${port}_${timestamp}.csv"
        echo "elapsed_time,current_reading" > "$output_file"
    fi
    
    echo "Logging current draw for port $port"
    echo "Hardware path: $hwmon_path"
    if [[ -n "$output_file" ]]; then
        echo "Saving to: $output_file"
    fi
    if [[ -n "$duration" ]]; then
        echo "Duration: $duration seconds"
    else
        echo "Duration: unlimited (Ctrl+C to stop)"
    fi
    echo "Time(s)    Current(mA)"
    echo "-------------------"
    
    local start_time=$(date +%s%N)
    local end_time=0
    
    if [[ -n "$duration" ]]; then
        end_time=$((start_time + duration * 1000000000))
    fi
    
    # Setup signal handler for clean exit
    trap 'echo -e "\nLogging stopped."; exit 0' SIGINT SIGTERM
    
    while true; do
        local now=$(date +%s%N)
        local elapsed=$(echo "scale=3; ($now - $start_time) / 1000000000" | bc -l)
        local reading=$(cat "$hwmon_path")
        local current_ma=$(echo "$reading" | bc -l | awk '{printf "%d", ($1+0.5)}')
        
        # Print to console
        printf "%8.3f   %6d\n" "$elapsed" "$current_ma"
        
        # Save to CSV if requested
        if [[ "$save_csv" == "true" ]]; then
            echo "$elapsed,$reading" >> "$output_file"
        fi
        
        # Check if duration exceeded
        if [[ $end_time -gt 0 && $now -ge $end_time ]]; then
            break
        fi
        
        sleep 0.01
    done
    
    echo
    if [[ "$save_csv" == "true" ]]; then
        local line_count=$(wc -l < "$output_file")
        echo "Logging completed. Data saved to: $output_file"
        echo "Total measurements: $((line_count - 1))"
    else
        echo "Logging completed."
    fi
}

# Parse arguments
if [[ $# -eq 0 ]]; then
	print_usage
	exit 1
fi

# Help option
if [[ "$1" = "-h" || "$1" = "--help" || "$1" = "-help" ]]; then
	print_usage
	exit 0
fi


# Parse main arguments
port="$1"
duration=""
save_csv="false"

# Parse remaining arguments
shift
while [[ $# -gt 0 ]]; do
	case "$1" in
		-s|--save)
			save_csv="true"
			;;
		[0-9]*)
			duration="$1"
			;;
		*)
			echo "Error: Unknown argument '$1'" >&2
			print_usage
			exit 1
			;;
	esac
	shift
done

# Validate port
if ! validate_port "$port"; then
	echo "Error: Invalid port '$port'. Valid ports are: $(list_ports)" >&2
	exit 1
fi

# Start logging
log_current "$port" "$duration" "$save_csv"