<?php

function serviceStatusLabels() {
    return [
        'ok' => '정상',
        'maintenance' => '점검 중',
        'warning' => '일부 오류',
        'unknown' => '확인 필요',
    ];
}

function serviceStatusLabel($status) {
    $labels = serviceStatusLabels();
    return $labels[(string)$status] ?? $labels['unknown'];
}

function serviceStatusClass($status) {
    $status = (string)$status;
    return array_key_exists($status, serviceStatusLabels()) ? $status : 'unknown';
}

function serviceStatusMaintenance() {
    $enabled = settingBool('service_maintenance_enabled', false);
    $title = trim(maskInternalPathText(ensureUtf8String(getSetting('service_maintenance_title', '서비스 점검 안내'))));
    $message = trim(maskInternalPathText(ensureUtf8String(getSetting('service_maintenance_message', ''))));
    $updatedAt = getSetting('service_maintenance_updated_at', '');
    return [
        'enabled' => $enabled,
        'title' => $title !== '' ? $title : '서비스 점검 안내',
        'message' => $message,
        'updated_at' => $updatedAt,
    ];
}

function serviceStatusScalar($sql, $params = [], $fallback = 0) {
    try {
        $stmt = getDBConnection()->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchColumn();
    } catch (Throwable $e) {
        return $fallback;
    }
}

function serviceStatusRecentLogCount($level = null, $typeLike = null) {
    $where = ['created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)'];
    $params = [];
    if ($level !== null) {
        $where[] = 'log_level = :level';
        $params[':level'] = $level;
    }
    if ($typeLike !== null) {
        $where[] = 'log_type LIKE :type_like';
        $params[':type_like'] = '%' . $typeLike . '%';
    }
    return (int)serviceStatusScalar('SELECT COUNT(*) FROM app_logs WHERE ' . implode(' AND ', $where), $params, 0);
}

function serviceStatusBackupSummary() {
    try {
        $dir = ensureBackupDir();
        $files = glob($dir . '/music_backup_*.json') ?: [];
        rsort($files);
        $latest = $files ? date('Y-m-d H:i', filemtime($files[0])) : null;
        return ['count' => count($files), 'latest' => $latest, 'ok' => is_dir($dir) && is_writable($dir)];
    } catch (Throwable $e) {
        return ['count' => 0, 'latest' => null, 'ok' => false];
    }
}

function getServiceStatusSummary($admin = false) {
    $maintenance = serviceStatusMaintenance();
    $scanErrors = (int)serviceStatusScalar("
        SELECT COALESCE(SUM(metadata_error_count), 0)
        FROM scan_logs
        WHERE scan_finished_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ", [], 0);
    $lastScan = null;
    try {
        $stmt = getDBConnection()->prepare("
            SELECT scan_finished_at, metadata_error_count, message
            FROM scan_logs
            WHERE scan_finished_at IS NOT NULL
            ORDER BY scan_finished_at DESC, id DESC
            LIMIT 1
        ");
        $stmt->execute();
        $lastScan = $stmt->fetch() ?: null;
    } catch (Throwable $e) {
        $lastScan = null;
    }

    $playbackFailures = (int)serviceStatusScalar("
        SELECT COUNT(*)
        FROM app_playback_failures
        WHERE status IN ('new', 'reviewing')
           OR last_seen_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ", [], 0);
    $errorLogs = serviceStatusRecentLogCount('error');
    $apiErrors = serviceStatusRecentLogCount(null, 'api');
    $backup = serviceStatusBackupSummary();
    $pwaEnabled = settingBool('pwa_enabled', true);

    $items = [
        [
            'key' => 'playback',
            'label' => '재생 기능',
            'status' => $playbackFailures > 0 ? 'warning' : 'ok',
            'public_detail' => $playbackFailures > 0 ? '일부 곡 재생 상태 확인 중' : '음악 재생 가능',
            'admin_detail' => $playbackFailures > 0 ? number_format($playbackFailures) . '건 확인 필요' : '최근 재생 실패 이슈 없음',
        ],
        [
            'key' => 'scan',
            'label' => '음악 스캔',
            'status' => $scanErrors > 0 ? 'warning' : 'ok',
            'public_detail' => $lastScan ? '최근 스캔 완료' : '스캔 기록 확인 필요',
            'admin_detail' => $lastScan ? ('최근 스캔 ' . $lastScan['scan_finished_at'] . ' / 오류 ' . number_format($scanErrors) . '건') : '최근 스캔 기록 없음',
        ],
        [
            'key' => 'cover',
            'label' => '앨범아트',
            'status' => 'ok',
            'public_detail' => '앨범아트 표시 가능',
            'admin_detail' => 'cover.php 경유 제공',
        ],
        [
            'key' => 'lyrics',
            'label' => '가사 기능',
            'status' => 'ok',
            'public_detail' => '가사 조회 및 등록 가능',
            'admin_detail' => 'lyrics 테이블 기준',
        ],
        [
            'key' => 'pwa',
            'label' => 'PWA / 오프라인',
            'status' => $pwaEnabled ? 'ok' : 'unknown',
            'public_detail' => $pwaEnabled ? '설치형 앱 지원' : 'PWA 설치 안내 비활성',
            'admin_detail' => $pwaEnabled ? 'service-worker 활성 대상' : '설정에서 PWA 비활성',
        ],
        [
            'key' => 'backup',
            'label' => '백업',
            'status' => $backup['ok'] ? 'ok' : 'warning',
            'public_detail' => $backup['ok'] ? '백업 저장소 준비됨' : '백업 상태 확인 필요',
            'admin_detail' => ($backup['latest'] ? '최근 백업 ' . $backup['latest'] . ' / ' : '') . number_format($backup['count']) . '개 파일',
        ],
        [
            'key' => 'errors',
            'label' => '최근 오류',
            'status' => $errorLogs > 0 || $apiErrors > 0 ? 'warning' : 'ok',
            'public_detail' => $errorLogs > 0 || $apiErrors > 0 ? '일부 오류 확인 중' : '최근 주요 오류 없음',
            'admin_detail' => '오류 ' . number_format($errorLogs) . '건 / API 관련 ' . number_format($apiErrors) . '건',
        ],
    ];

    $overall = $maintenance['enabled'] ? 'maintenance' : 'ok';
    foreach ($items as $item) {
        if ($item['status'] === 'warning') {
            $overall = $overall === 'maintenance' ? 'maintenance' : 'warning';
            break;
        }
    }

    return [
        'overall' => $overall,
        'maintenance' => $maintenance,
        'items' => $items,
        'admin' => [
            'playback_failures' => $playbackFailures,
            'scan_errors' => $scanErrors,
            'error_logs' => $errorLogs,
            'api_errors' => $apiErrors,
        ],
    ];
}

function renderServiceStatusBanner($basePath = './') {
    $maintenance = serviceStatusMaintenance();
    if (!$maintenance['enabled']) return;
    ?>
    <section class="service-status-banner status-maintenance" id="service-status-banner" aria-label="서비스 점검 안내">
        <div class="service-status-banner-icon" aria-hidden="true"><i class="fa-solid fa-screwdriver-wrench"></i></div>
        <div class="service-status-banner-content">
            <strong><?php echo h($maintenance['title']); ?></strong>
            <?php if ($maintenance['message'] !== ''): ?><p><?php echo nl2br(h($maintenance['message'])); ?></p><?php endif; ?>
        </div>
        <a class="btn btn-secondary btn-sm" href="<?php echo h($basePath . 'status.php'); ?>">상태 보기</a>
    </section>
    <?php
}
