#!/bin/sh
# Extract to stdout normalised (archived, not live) microinverter 1.

# The output record/line format is:
#YYYY-MM,device,coverage,exp,comment

# Input file(s) glob pattern, ALSO PARSED FROM OUTSIDE this script.
INPUTGLOB="data/mi1/log/20????-LB.log.gz"

# List of candidiate archived data files, in lexical order.
CANDS="$(ls -1 $INPUTGLOB)"


# Create header.
echo "#YYYY-MM,device,coverage,exp,comment"
# List input files.
for f in $CANDS;
    do
    echo '#input,"'"$f"'"'
    done

# Simple input format, using Power (W) * 10 min interval.
# Low PF (<0.25) can be assumed to be parasitic self-consumption.
# There should be at least one record each day even if zero or near.
#2026-07-20T13:51:55Z {"StatusSNS":{"Time":"2026-07-20T14:51:56","ENERGY":{"TotalStartTime":"2022-10-05T19:17:26","Total":3.111,"Yesterday":0.004,"Today":0.061,"Power":29.3,"ApparentPower":30.0,"ReactivePower":6.5,"Factor":0.98,"Voltage":244,"Current":0.123}}}
#2026-07-20T14:52:06Z {"StatusSNS":{"Time":"2026-07-20T15:52:06","ENERGY":{"TotalStartTime":"2022-10-05T19:17:26","Total":3.116,"Yesterday":0.004,"Today":0.067,"Power":28.6,"ApparentPower":30.6,"ReactivePower":10.8,"Factor":0.94,"Voltage":245,"Current":0.125}}}


# Create by-month records.
# Assume for now that:
#   * each input file is one month
#   * each record is 10 minutes
#   * coverage is full for day if at least one record that day
#   * generation is negative (parasitic load) if power factor < 0.25
for f in $CANDS;
do
    gzip -d < $f | \
        sh script/LBPowerExtract.sh -pf | \
        awk '{
            date=substr($1, 1, 10);
            if(date != lastdate) { ++days; lastdate=date; }
            W = $2;
            if($3 < 0.25) { W = -W; }
            TotalWh += W / 6;
            YYYYMM=substr($1, 1, 7);
            }
        END {
            coverage=1
            if(days < 28) { coverage = days/28; }
            printf("%s,LB,%.2f,%.1f\n", YYYYMM, coverage, TotalWh/1000);
            }'
done | sort
