#!/usr/bin/perl
use JSON;
my $factcheckurl = "https://leadstories.com/hoax-alert/2023/09/fact-check-demo-video-does-not-prove-a-laser-caused-hawaiis-maui-fires-because-blue-items-survived.html";

my $frame0url = $factcheckurl;
my $frame1url = $factcheckurl;
my $frame2url = $factcheckurl;
my $frame3url = $factcheckurl;
my $stringsurl = $factcheckurl;

$frame0url =~ s/(leadstories\.com\/)/$1frame0\//;
$frame1url =~ s/(leadstories\.com\/)/$1frame1\//;
$frame2url =~ s/(leadstories\.com\/)/$1frame2\//;
$frame3url =~ s/(leadstories\.com\/)/$1frame3\//;
$stringsurl =~ s/(leadstories\.com\/)/$1strings\//;

print $stringsurl;
my $stringsjson = `wget -O - '$stringsurl'`;
print $stringsjson;
my $decoded_json = decode_json($stringsjson);

generate_audio("question", $decoded_json->{question}, "fast");
generate_audio("secondsentence", $decoded_json->{secondsentence});
generate_audio("lastpart", $decoded_json->{lastpart}." Full details on lead stories dot com.");


`google-chrome --headless --silent --screenshot=frame0.png --window-size=1080,1920 --no-sandbox --hide-scrollbars '$frame0url'`;
`google-chrome --headless --silent --screenshot=frame1.png --window-size=1080,1920 --no-sandbox --hide-scrollbars '$frame1url'`;
`google-chrome --headless --silent --screenshot=frame2.png --window-size=1080,1920 --no-sandbox --hide-scrollbars '$frame2url'`;
`google-chrome --headless --silent --screenshot=frame3.png --window-size=1080,1920 --no-sandbox --hide-scrollbars '$frame3url'`;

my $questionduration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 question.mp3`;
my $funnysoundduration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 honk.mp3`;
my $secondsentenceduration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 secondsentence.mp3`;
my $lastpartduration = `ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 lastpart.mp3`;

chomp $questionduration;
chomp $funnysoundduration;
chomp $secondsentenceduration;
chomp $lastpartduration;


system("ffmpeg -y -loop 1 -i frame0.png -i question.mp3 -r 25 -c:v libx264 -c:a aac -b:a 192k -ar 48000 -pix_fmt yuv420p -t $questionduration question.mp4");
system("ffmpeg -y -loop 1 -i frame1.png -i honk.mp3 -r 25 -c:v libx264 -c:a aac -b:a 192k -ar 48000 -pix_fmt yuv420p -t $funnysoundduration nodear.mp4");
system("ffmpeg -y -loop 1 -i frame2.png -i secondsentence.mp3 -r 25 -c:v libx264 -c:a aac -b:a 192k -ar 48000 -pix_fmt yuv420p -t $secondsentenceduration secondsentence.mp4");
system("ffmpeg -y -loop 1 -i frame3.png -i lastpart.mp3 -r 25 -c:v libx264 -c:a aac -b:a 192k -ar 48000 -pix_fmt yuv420p -t $lastpartduration lastpart.mp4");

# example command to make a picture in picture video
# ffmpeg -y -i lasers.mp4 -i question.mp4 -filter_complex "[0]scale=300:-1 [pip]; [1][pip] overlay=main_w/2-overlay_w/2:160" -map 1:a -t 12.96 pip.mp4
# Working youtube downloader https://github.com/yt-dlp/yt-dlp#release-files

`ffmpeg -y -safe 0 -f concat -i filelist.txt -c copy output.mp4`;
`ffmpeg -y -i output.mp4 -i the-breaking-news-161462.mp3 -filter_complex "[0:a]volume=1[a0]; [1:a]volume=0.10[a1]; [a0][a1]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -c:a aac -shortest -ac 2 output_with_music.mp4`;
`ffmpeg -y -safe 0 -f concat -i filelist2.txt -c copy final.mp4`;

sub generate_audio (){
	my $filename = shift;
	my $text = shift;
	my $mode = shift;
	my %jsondata;
	if ($mode eq "fast"){
		$jsondata{"audioConfig"}{"speakingRate"} = "1.1";
		$jsondata{"audioConfig"}{"pitch"} = "-5";
	}

	$jsondata{"voice"}{"languageCode"} = "en-US";
	$jsondata{"voice"}{"name"} = "en-US-Neural2-G";
	$jsondata{"voice"}{"ssmlGender"} = "Female";
	$jsondata{"audioConfig"}{"audioEncoding"} = "MP3";
	$jsondata{"input"}{"text"} = $text;
	my $json = encode_json (\%jsondata);

	open(JSONFILE, ">", "/tmp/jsonfile.txt");
	print JSONFILE $json;
	close JSONFILE;

	my $audiocontent;
	my $failed;

	while (! $audiocontent){
	  if ($failed){print "Google API failed $failed times so far\n";sleep 5};
	# Send to Google TTS API
	`curl -H "Content-Type: application/json; charset=utf-8" -d @/tmp/jsonfile.txt "https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=AIzaSyBLwdIl5e7NgLEs4SXwjpriK5NiVgwVKMc" >/tmp/voicejson.txt`;

	# Parse json
	open(my $fh, '<:encoding(UTF-8)', "/tmp/voicejson.txt")  or die "Could not open file /tmp/voicejson.txt";
	my $returnjson;
	while (<$fh>) {
	  $returnjson .= $_;
	}
	my $decoded_json = decode_json($returnjson);

	$audiocontent = $decoded_json->{"audioContent"};
	if (! $audiocontent){print $decoded_json->{"error"}->{"message"}."\n";$failed++}
	}

	# Save base64 audio
	open(BASE64FILE, ">", "/tmp/audiobase64.txt");
	print BASE64FILE $audiocontent;
	close BASE64FILE;

	# Convert & save
	system("base64 /tmp/audiobase64.txt --decode > ".$filename.".mp3");
}	