#!/usr/bin/perl

#(9/7/2022): Run the Timeseries Insights API over a period of time in a rolling window.

$PROJECTID = '';
$DATASET = 'monkeypox';
#$STARTDATE = 20220506000000;
#$ENDDATE =   20220508235959;
$STARTDATE = 20220507120000;
$ENDDATE =   20220507140000;
$STEP = 15 * 60;

use POSIX qw(mktime);
use JSON::XS;

unlink("./TIMELINE.csv"); 
open(OUT, ">./TIMELINE.csv"); print OUT "Date,Score,Forecast,Actual,Deviation\n"; close(OUT);

#########################################################################################
#get our bearer token...-H \"Authorization: Bearer \$(gcloud auth application-default print-access-token)\"
$bearertoken = `gcloud auth application-default print-access-token`; $bearertoken=~s/\s+$//s;
print "GOT TOKEN: $bearertoken\n";
#########################################################################################

#########################################################################################
#SUBMIT TO THE API...

#convert dates to UNIX time...
$ENV{TZ} = 'UTC'; #ensure mktime converts to UTC...
($year, $mon, $mday, $hour, $min, $sec) = $STARTDATE=~/^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/; $start_unix = mktime($sec, $min, $hour, $mday, $mon-1, $year-1900);
($year, $mon, $mday, $hour, $min, $sec) = $ENDDATE=~/^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/; $end_unix = mktime($sec, $min, $hour, $mday, $mon-1, $year-1900);

#and loop...
$datetime = $start_unix;
while($datetime <= $end_unix) {
    ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($datetime); $mon++; $year+=1900;
    $datetime_json = sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year, $mon, $mday, $hour, $min, $sec);
    $datetime_human = sprintf("%d/%d/%04d %02d:%02d:%02d", $mon, $mday, $year, $hour, $min, $sec);
    print "Running API For DateTime: $datetime_json\n";
    
    #run the query...
    $ret = ''; $ret = `curl -s -H "Content-Type: application/json" -H "X-Goog-User-Project: $PROJECTID" -H "Authorization: Bearer $bearertoken"  https://timeseriesinsights.googleapis.com/v1/projects/$PROJECTID/datasets/monkeypox:query -d '{
	detectionTime: "$datetime_json",
	slicingParams: {
	    dimensionNames: ["topic"]
	},
	timeseriesParams: {
	    forecastHistory: "259200s",
	    granularity: "3600s"
	},
	forecastParams: {
	    seasonalityHint: "DAILY",
	    noiseThreshold: 1
	},
	numReturnedSlices: 1
    }'`;
    
    #parse the results to get the anomaly score of the highest scored slice...
    #print "($ret)\n";
    undef($ref); $ref = decode_json($ret);
    $score = 0 + $ref->{'slices'}[0]->{'anomalyScore'};
    $forecast = 0 + $ref->{'slices'}[0]->{'detectionPointForecast'};
    $actual = 0 + $ref->{'slices'}[0]->{'detectionPointActual'};
    $deviation = 0 + $ref->{'slices'}[0]->{'expectedDeviation'};
    print "\tScore: ($score)\n";
    
    #and write to our output file...
    open(OUT, ">>./TIMELINE.csv"); print OUT "$datetime_human,$score,$forecast,$actual,$deviation\n"; close(OUT);
        
    #increment by our step and continue...
    $datetime+=$STEP;
}

#########################################################################################
