<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\Recommendations\FeedOfflineEvaluationService;
use Illuminate\Console\Command;

final class EvaluateFeedWeightsCommand extends Command
{
    protected $signature = 'analytics:evaluate-feed-weights
                            {--algo= : Optional algo_version to evaluate}
                            {--from= : Start date (Y-m-d), defaults to last 30 days}
                            {--to= : End date (Y-m-d), defaults to today}
                            {--json : Output as JSON}';

    protected $description = 'Offline feed weight evaluation using feed_daily_metrics';

    public function __construct(private readonly FeedOfflineEvaluationService $evaluator)
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $from = (string) ($this->option('from') ?: now()->subDays(29)->toDateString());
        $to = (string) ($this->option('to') ?: now()->toDateString());
        $algo = $this->option('algo') ? (string) $this->option('algo') : null;

        if ($from > $to) {
            $this->error('Invalid range: --from must be <= --to');
            return self::FAILURE;
        }

        if ($algo !== null && $algo !== '') {
            $result = $this->evaluator->evaluateAlgo($algo, $from, $to);

            if ((bool) $this->option('json')) {
                $this->line((string) json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            } else {
                $this->table(
                    ['algo_version', 'ctr', 'save_rate', 'long_dwell_share', 'bounce_rate', 'objective_score'],
                    [[
                        (string) $result['algo_version'],
                        (float) $result['ctr'],
                        (float) $result['save_rate'],
                        (float) $result['long_dwell_share'],
                        (float) $result['bounce_rate'],
                        (float) $result['objective_score'],
                    ]]
                );
            }

            return self::SUCCESS;
        }

        $results = $this->evaluator->evaluateAll($from, $to);

        if ((bool) $this->option('json')) {
            $this->line((string) json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            return self::SUCCESS;
        }

        $rows = array_map(static fn (array $row): array => [
            (string) $row['algo_version'],
            (float) $row['ctr'],
            (float) $row['save_rate'],
            (float) $row['long_dwell_share'],
            (float) $row['bounce_rate'],
            (float) $row['objective_score'],
        ], $results);

        $this->table(
            ['algo_version', 'ctr', 'save_rate', 'long_dwell_share', 'bounce_rate', 'objective_score'],
            $rows
        );

        return self::SUCCESS;
    }
}
