<?php

namespace App\Console\Commands;

use App\Models\Fish\Species;
use App\Models\Fish\StaticFeaturesGrid;
use App\Models\Fish\StaticHabitatScore;
use App\Services\FishScore\FishScoreEngine;
use Illuminate\Console\Command;

class RebuildFishStaticHabitatScores extends Command
{
    protected $signature = 'fish:rebuild-static-habitat-scores
                            {--species=* : Belirli tür ID\'leri (boşsa tüm published)}
                            {--chunk=300 : Grid chunk boyutu}';

    protected $description = 'static_habitat_scores tablosunu static_features_grid üzerinden yeniden hesaplar.';

    public function handle(FishScoreEngine $engine): int
    {
        $speciesIds = collect($this->option('species'))
            ->filter(fn ($id) => $id !== null && $id !== '')
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();

        if ($speciesIds->isEmpty()) {
            $speciesIds = Species::published()->pluck('id');
        }

        if ($speciesIds->isEmpty()) {
            $this->warn('İşlenecek tür yok.');

            return self::SUCCESS;
        }

        $chunk = max(50, (int) $this->option('chunk'));
        $totalGrids = StaticFeaturesGrid::query()->count();

        if ($totalGrids === 0) {
            $this->warn('static_features_grid boş — önce grid ingest çalıştırın.');

            return self::SUCCESS;
        }

        $totalCells = $totalGrids * $speciesIds->count();
        $this->info("Grid satırı: {$totalGrids}, tür sayısı: ".$speciesIds->count());

        $bar = $this->output->createProgressBar($totalCells);
        $bar->start();

        StaticFeaturesGrid::query()->orderBy('id')->chunkById($chunk, function ($grids) use ($engine, $speciesIds, $bar) {
            foreach ($grids as $grid) {
                $lat = (float) $grid->lat;
                $lon = (float) $grid->lon;

                foreach ($speciesIds as $sid) {
                    $score = $engine->calculateHabitatScoreOnly($lat, $lon, (int) $sid);
                    StaticHabitatScore::query()->updateOrCreate(
                        ['species_id' => $sid, 'grid_id' => $grid->id],
                        ['habitat_score' => $score, 'computed_at' => now()]
                    );
                    $bar->advance();
                }
            }
        });

        $bar->finish();
        $this->newLine();
        $this->info('Tamamlandı.');

        return self::SUCCESS;
    }
}
