<?php

namespace App\Http\Controllers\AiPortal;

use App\Models\AiAction;
use App\Models\Server;
use App\Models\Ticket;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    /**
     * Single endpoint that powers the Dashboard page. Bundles everything to
     * minimize round-trips on initial load.
     */
    public function index()
    {
        $now = now();

        return response()->json([
            'active_ai_ops'      => AiAction::where('status', AiAction::STATUS_RUNNING)->count(),
            'pending_approvals'  => AiAction::where('status', AiAction::STATUS_PENDING)->count(),
            'open_tickets'       => Ticket::whereIn('status', [
                Ticket::STATUS_OPEN, Ticket::STATUS_AI_DRAFTED,
            ])->count(),

            'servers_by_status'  => Server::select('status', DB::raw('count(*) as count'))
                ->groupBy('status')->pluck('count', 'status'),

            'today_ai_spend_usd' => DB::table('ai_costs')
                ->where('called_at', '>=', $now->copy()->startOfDay())
                ->sum('cost_usd'),

            'spend_by_provider' => DB::table('ai_costs')
                ->where('called_at', '>=', $now->copy()->startOfDay())
                ->select('provider', DB::raw('SUM(cost_usd) as total'))
                ->groupBy('provider')
                ->pluck('total', 'provider'),

            // 24h activity series — actions per hour.
            'activity_24h' => $this->activityHourly($now),

            'critical_alerts'    => $this->criticalAlerts(),
        ]);
    }

    private function activityHourly($now): array
    {
        $start = $now->copy()->subHours(23)->startOfHour();

        // Cross-DB hour bucket: pull rows in window, bucket in PHP. Cheap when
        // the window is bounded to 24h. Avoids DB-specific HOUR() / strftime().
        $rows = DB::table('ai_actions')
            ->where('created_at', '>=', $start)
            ->select('created_at')
            ->get();

        $buckets = array_fill(0, 24, 0);
        foreach ($rows as $r) {
            $h = (int) date('G', strtotime($r->created_at));
            $buckets[$h]++;
        }

        return collect(range(0, 23))->map(fn ($i) => [
            'hour'     => ($start->hour + $i) % 24,
            'commands' => $buckets[($start->hour + $i) % 24],
        ])->all();
    }

    private function criticalAlerts(): array
    {
        // Top 10 highest-severity unresolved issues across the fleet.
        return DB::table('issues')
            ->join('servers', 'issues.server_id', '=', 'servers.id')
            ->where('issues.status', 'open')
            ->whereIn('issues.severity', ['critical', 'high'])
            ->orderByDesc('issues.detected_at')
            ->limit(10)
            ->select('issues.id', 'issues.severity', 'issues.title', 'issues.detected_at',
                     'servers.hostname as server_hostname')
            ->get()->map(fn ($r) => (array) $r)->all();
    }

    /**
     * Recent AI activity (last 10 actions) for the live stream display.
     * Picked separately from dashboard summary so the stream can be polled
     * faster than the rest if we want.
     */
    public function activity()
    {
        $rows = DB::table('ai_actions')
            ->leftJoin('servers', 'ai_actions.server_id', '=', 'servers.id')
            ->orderByDesc('ai_actions.created_at')
            ->limit(10)
            ->select(
                'ai_actions.id', 'ai_actions.command', 'ai_actions.status',
                'ai_actions.ai_model', 'ai_actions.risk',
                'ai_actions.created_at', 'ai_actions.executed_at', 'ai_actions.completed_at',
                'servers.hostname as server_hostname'
            )
            ->get();

        return response()->json($rows);
    }
}
