<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class DownloadCreditsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:download-credits-command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    private $processingUnits = [];

    private $totalSum = 0;
    private $totalCount = 0;
    private $allValues = [];
    private $stdDev = 0;
    private $overallAvg;

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $path = 'Bagamoyo_trial/single_images/';
        $datesDir = Storage::directories($path);

        $this->extractData($datesDir);
//        dd($this->processingUnits);
        $this->calculateStatistics();

        // Output the statistics
        $this->info('Total sum: '.$this->totalSum);
        $this->info('Total count: '.$this->totalCount);
        $this->info('Overall average: '.$this->overallAvg);
        $this->info('Standard deviation: '.$this->stdDev);
    }

    private function extractProcessingUnitsFromFile($filePath)
    {
        $data = json_decode(Storage::get($filePath), true);
        $responseHeaders = $data['response']['headers'];
        $processingUnits = $responseHeaders['x-processingunits-spent'];
        return $processingUnits;
    }

    private function calculateStatistics()
    {
        foreach ($this->processingUnits as $date => $values) {
            $processingUnitsPerDate = array_sum($values);
            $this->totalSum += $processingUnitsPerDate;
            $this->totalCount++;
            $this->allValues[$date] = $processingUnitsPerDate;
        }

        $this->overallAvg = $this->totalSum / $this->totalCount;
        $variance = array_reduce($this->allValues, function ($carry, $item) {
                return $carry + pow($item - $this->overallAvg, 2);
            }, 0) / $this->totalCount;

        $this->stdDev = sqrt($variance);
    }

    private function extractData(array $datesDir): void
    {
        foreach ($datesDir as $dateDir) {
            $date = basename($dateDir);
            $subdirectories = Storage::directories($dateDir);
            $this->processingUnits[$date] = [];

            foreach ($subdirectories as $subdirectory) {
                $requestPath = $subdirectory.'/request.json';
                if (Storage::fileExists($requestPath)) {
                    $this->processingUnits[$date][] = $this->extractProcessingUnitsFromFile($requestPath);
                }
            }
        }
    }
}
