#!/usr/bin/env bash

#######################
# MAIN script body
#######################

. /hive/miners/custom/tnminer0.4.9ml/h-manifest.conf

# Get the latest stats line from log
stats_raw=`cat $CUSTOM_LOG_BASENAME.log | grep -E "G[0-9]+: [0-9.]+ Mh" | tail -n 1`
echo "stats_raw: $stats_raw"

#Calculate miner log freshness
maxDelay=120
time_now=$(date -u +%s)  # UTC
echo "time_now : $time_now"

# Check if we have valid stats data
if [[ -n "$stats_raw" ]]; then
    # Extract total hashrate from string like "Total: 31.41 Mh/s"
    total_hashrate_str=`echo $stats_raw | grep -o 'Total: [0-9.]* Mh/s' | cut -d' ' -f2 | sed 's/Mh\/s//'`
    total_hashrate=`echo "$total_hashrate_str * 1000" | bc | cut -d'.' -f1`
    
    # Extract A/R values (accepted/rejected shares)
    ar_raw=`echo $stats_raw | grep -o 'A/R: [0-9/]*/[0-9/]*' | cut -d' ' -f2`
    if [[ -n "$ar_raw" ]]; then
        accepted=`echo $ar_raw | cut -d'/' -f1`
        rejected=`echo $ar_raw | cut -d'/' -f2`
    else
        accepted=0
        rejected=0
    fi
    
    diffTime=0  # Consider log as fresh since we're reading latest entry
else
    total_hashrate=0
    accepted=0
    rejected=0
    diffTime=999
fi

echo "diffTime : $diffTime"
if [ "$diffTime" -lt "$maxDelay" ]; then
    echo "total_hashrate : $total_hashrate"
    echo "accepted : $accepted"
    echo "rejected : $rejected"

    #GPU Status
    gpu_stats=$(< $GPU_STATS_JSON)
    #echo "GPU_STATS_JSON: $GPU_STATS_JSON" >&2
    #cat "$GPU_STATS_JSON" >&2
    
    echo "GPU_STATS_JSON=$GPU_STATS_JSON" >&2
    ls -l "$GPU_STATS_JSON" >&2
    jq --slurp -r -c '.[] | .busids, .brand, .temp, .fan | join(" ")' "$GPU_STATS_JSON" >&2

    readarray -t gpu_stats < <( jq --slurp -r -c '.[] | .busids, .brand, .temp, .fan | join(" ")' $GPU_STATS_JSON 2>/dev/null)
    busids=(${gpu_stats[0]})
    brands=(${gpu_stats[1]})
    temps=(${gpu_stats[2]})
    fans=(${gpu_stats[3]})
    gpu_count=${#busids[@]}

    hash_arr=()
    busid_arr=()
    fan_arr=()
    temp_arr=()
    lines=()

    if [ $(gpu-detect NVIDIA) -gt 0 ]; then
        brand_gpu_count=$(gpu-detect NVIDIA)
        BRAND_MINER="nvidia"
    elif [ $(gpu-detect AMD) -gt 0 ]; then
        brand_gpu_count=$(gpu-detect AMD)
        BRAND_MINER="amd"
    fi
    total_hashrate_sum_hs=0  # Initialize the variable
    # Determine shift for integrated video card
    [[ ${brands[0]} == 'cpu' ]] && internalCpuShift=1 || internalCpuShift=0
    
    for(( i=0; i < gpu_count; i++ )); do
        # Filter integrated video card (cpu)
        if [[ "${brands[i]}" == 'cpu' ]]; then
            continue
        fi
        
        [[ "${busids[i]}" =~ ^([A-Fa-f0-9]+): ]]
        busid_arr+=($((16#${BASH_REMATCH[1]})))
        temp_arr+=(${temps[i]})
        fan_arr+=(${fans[i]})                
        
        # Calculate correct GPU index considering integrated video card
        gpu_index_for_log=$i
        if [[ $internalCpuShift -eq 1 ]]; then
            gpu_index_for_log=$((i - internalCpuShift))
        fi
        
        # Search for GPU hashrate in new format (G1: 15.38 Mh)
        gpu_raw=$(echo "$stats_raw" | grep -o "G$((gpu_index_for_log+1)): [0-9.]* Mh")
        echo "gpu_raw : $gpu_raw"  
        
        if [[ -n "$gpu_raw" ]]; then
            # Extract hashrate from string like "G1: 15.38 Mh"
            hashrate_str=$(echo "$gpu_raw" | cut -d' ' -f2)
            # Convert Mh to HS for individual GPU hashrate (to match example)
            hashrate_hs=$(awk -v v="$hashrate_str" 'BEGIN { printf("%.0f", v * 1000000) }')
        else
            # Fallback to old format - assume it's in kH/s, convert to HS
            gpu_raw=$(grep "Hashrate GPU #$gpu_index_for_log" "$CUSTOM_LOG_BASENAME.log" | tail -n 1 | tr -d '\000')
            hashrate_kh=$(echo "$gpu_raw" | awk '{print $NF}' | tr -d '\000' | cut -d "." -f1)
            hashrate_hs=$(awk -v v="$hashrate_kh" 'BEGIN { printf("%.0f", v * 1000) }')
        fi

        echo "hashrate_hs: $hashrate_hs"
        # Keep as HS for HiveOS compatibility (like in the example)
        hash_arr+=($hashrate_hs)		
        total_hashrate_sum_hs=$((total_hashrate_sum_hs + hashrate_hs))
        echo "hash_arr : $hash_arr (HS)"
    done

    # Create JSON array for hash rates
    if [ ${#hash_arr[@]} -gt 0 ]; then
        hash_json=$(printf '%s\n' "${hash_arr[@]}" | jq -sR 'split("\n")[:-1] | map(tonumber)')
    else
        hash_json="[]"
    fi
    
    bus_numbers=`printf '%s\n' "${busid_arr[@]}"  | jq -cs '.'`
    fan_json=`printf '%s\n' "${fan_arr[@]}"  | jq -cs '.'`
    temp_json=`printf '%s\n' "${temp_arr[@]}"  | jq -cs '.'`

    uptime=$(( `date +%s` - `stat -c %Y $CUSTOM_CONFIG_FILENAME` ))

    #Compile stats (using HS units like in example)
    stats=$(jq -nc \
            --argjson hs "$hash_json"\
            --arg hs_units "hs" \
            --arg ths "$total_hashrate_sum_hs" \
            --arg algo "BLAKE3" \
            --arg ver "$CUSTOM_VERSION" \
            --arg ac "$accepted" \
            --arg rj "$rejected" \
            --arg uptime "$uptime" \
            --arg bus "$bus_numbers" \
            --arg temp "$temp_json" \
            --arg fan "$fan_json" \
            '{
                hs: $hs,
                hs_units: $hs_units,
                ths: ($ths | tonumber),
                algo: $algo,
                ver: $ver,
                ar: [($ac|tonumber), ($rj|tonumber)],
                uptime: ($uptime|tonumber),
                bus_numbers: ($bus | try fromjson // []),
                temp: ($temp | try fromjson // []),
                fan: ($fan | try fromjson // [])
            }')
    # Calculate khs for total hashrate (first output line)
    khs=$((total_hashrate_sum_hs / 1000))
else
  khs=0
  accepted=0
  rejected=0
  stats="null"
fi

echo Debug info:
echo Log file : $CUSTOM_LOG_BASENAME.log
echo Time since last log entry : $diffTime
echo Raw stats : $stats_raw
echo KHS : $khs
echo Accepted : $accepted
echo Rejected : $rejected
echo Output : $stats

# Output in the correct format: khs first, then stats (like in the example)
echo "$khs"
echo "$stats"
