<?php
declare(strict_types=1);
namespace App\Services;

final class SecurityDashboardService
{
    /** @return array<string,mixed> */
    public function report(): array
    {
        $base = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 2);
        $events = $this->readJsonLines($base . '/storage/logs/security/security-events.log');
        $alerts = $this->readJsonLines($base . '/storage/logs/security/security-alerts.log');
        $since = time() - 86400;
        $recentEvents = array_values(array_filter($events, fn(array $r): bool => $this->timestamp($r) >= $since));
        $recentAlerts = array_values(array_filter($alerts, fn(array $r): bool => $this->timestamp($r) >= $since));
        $bySeverity = ['info'=>0,'warning'=>0,'error'=>0,'critical'=>0];
        $byEvent = [];
        foreach ($recentEvents as $row) {
            $severity = strtolower((string)($row['context']['severity'] ?? $row['severity'] ?? 'warning'));
            if (!isset($bySeverity[$severity])) $severity = 'warning';
            $bySeverity[$severity]++;
            $event = (string)($row['context']['event'] ?? $row['event'] ?? 'security.event');
            $byEvent[$event] = ($byEvent[$event] ?? 0) + 1;
        }
        arsort($byEvent);
        $checks = [
            'master_key' => trim((string)($_ENV['AXIOM_MASTER_KEY_BASE64'] ?? '')) !== '',
            'sodium' => extension_loaded('sodium'),
            'https_production' => (string)($_ENV['APP_ENV'] ?? 'local') !== 'production' || $this->isHttps(),
            'security_logs' => is_dir($base . '/storage/logs/security') && is_writable($base . '/storage/logs/security'),
            'private_storage' => is_dir($base . '/storage/private') && is_writable($base . '/storage/private'),
            'signed_updates' => is_file($base . '/config/update_signing_public.key'),
        ];
        $score = (int)round((count(array_filter($checks)) / max(1, count($checks))) * 100);
        return [
            'score'=>$score,
            'checks'=>$checks,
            'events_24h'=>count($recentEvents),
            'alerts_24h'=>count($recentAlerts),
            'severity'=>$bySeverity,
            'top_events'=>array_slice($byEvent,0,8,true),
            'recent_alerts'=>array_slice(array_reverse($recentAlerts),0,10),
            'generated_at'=>date('Y-m-d H:i:s'),
        ];
    }

    /** @return list<array<string,mixed>> */
    private function readJsonLines(string $file): array
    {
        if (!is_file($file) || !is_readable($file)) return [];
        $rows=[]; $handle=fopen($file,'rb'); if ($handle===false) return [];
        while (($line=fgets($handle))!==false) {
            $decoded=json_decode(trim($line),true);
            if (is_array($decoded)) $rows[]=$decoded;
            if (count($rows)>5000) array_shift($rows);
        }
        fclose($handle); return $rows;
    }

    /** @param array<string,mixed> $row */
    private function timestamp(array $row): int
    {
        foreach (['timestamp','datetime','date','created_at','time'] as $key) {
            if (!empty($row[$key])) { $ts=strtotime((string)$row[$key]); if ($ts!==false) return $ts; }
        }
        return time();
    }

    private function isHttps(): bool
    {
        return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
    }
}
