<?php

namespace App\Serp\Operations;

use App\Models\SerpCheck;
use App\Models\SerpOperationState;
use Illuminate\Support\Facades\DB;

final class SerpOperationsMetrics
{
    public function __construct(private ActivationManager $activation, private BudgetManager $budget, private CircuitBreaker $circuit, private RampUpPolicy $ramp) {}

    public function summary(): array
    {
        $since = now('UTC')->subDay();
        $counts = SerpCheck::where('created_at', '>=', $since)->select('status', 'execution_mode', DB::raw('count(*) aggregate'))->groupBy('status', 'execution_mode')->get();
        $total = $counts->sum('aggregate');
        $completed = $counts->where('status', 'completed')->sum('aggregate');
        $state = SerpOperationState::find(1);

        return ['activation_mode' => $this->activation->state()->value, 'kill_switch' => (bool) $state?->emergency_stopped_at, 'kill_reason' => $state?->emergency_reason_code, 'circuit_open' => $this->circuit->open(), 'last_health_at' => $state?->last_health_at, 'last_balance_micros' => $state?->last_balance_micros, 'last_error_category' => $state?->last_error_category, 'checks_24h' => $total, 'completed_24h' => $completed, 'failed_24h' => $counts->where('status', 'failed')->sum('aggregate'), 'success_percent' => $total ? round($completed * 100 / $total, 1) : 0, 'average_duration_ms' => (int) SerpCheck::where('created_at', '>=', $since)->whereNotNull('duration_ms')->avg('duration_ms'), 'average_polls' => (float) SerpCheck::where('created_at', '>=', $since)->avg('provider_poll_attempts'), 'stuck' => SerpCheck::whereIn('status', ['pending', 'running'])->where('updated_at', '<', now()->subMinutes((int) config('serp.stuck_after_minutes')))->count(), 'waiting_provider' => SerpCheck::where('status', 'running')->whereNotNull('provider_reference')->count(), 'budget' => $this->budget->usage(), 'ramp_up' => $this->ramp->status(), 'queue_backlog' => DB::table('jobs')->where('queue', config('serp.queue'))->count(), 'failed_jobs' => DB::table('failed_jobs')->count()];
    }
}
