<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/diagnostics.php';
require_once dirname(__DIR__) . '/includes/layout.php';
requirePermission('performance_view');

function safeDirSize($dir, $limit = 2000) {
    if (!is_dir($dir)) return 0;
    $size = 0;
    $count = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)) as $file) {
        if (++$count > $limit) break;
        if ($file->isFile()) $size += $file->getSize();
    }
    return $size;
}

function safeScalarCount($sql) {
    try {
        return (int)getDBConnection()->query($sql)->fetchColumn();
    } catch (Throwable $e) {
        return 0;
    }
}

$pdo = getDBConnection();
$searchIndexNames = ['idx_search_title', 'idx_search_artist', 'idx_search_album', 'idx_search_genre', 'idx_search_created_at', 'idx_search_play_count'];
$searchIndexCount = 0;
try {
    $placeholders = implode(',', array_fill(0, count($searchIndexNames), '?'));
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT index_name) FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = 'songs' AND index_name IN ($placeholders)");
    $stmt->execute($searchIndexNames);
    $searchIndexCount = (int)$stmt->fetchColumn();
} catch (Throwable $e) {
    $searchIndexCount = 0;
}
$metrics = [
    ['label' => '전체 곡 수', 'value' => number_format((int)$pdo->query("SELECT COUNT(*) FROM songs")->fetchColumn())],
    ['label' => '최근 24시간 재생 기록', 'value' => number_format((int)$pdo->query("SELECT COUNT(*) FROM play_history WHERE played_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)")->fetchColumn())],
    ['label' => 'play_history 총 개수', 'value' => number_format((int)$pdo->query("SELECT COUNT(*) FROM play_history")->fetchColumn())],
    ['label' => 'app_logs 총 개수', 'value' => number_format((int)$pdo->query("SELECT COUNT(*) FROM app_logs")->fetchColumn())],
    ['label' => 'scan_logs 총 개수', 'value' => number_format((int)$pdo->query("SELECT COUNT(*) FROM scan_logs")->fetchColumn())],
    ['label' => '앨범아트 캐시 파일', 'value' => number_format(count(glob(getCoverCacheDir() . '/*') ?: []))],
    ['label' => '커버 캐시 용량', 'value' => number_format(safeDirSize(getCoverCacheDir()) / 1024 / 1024, 2) . ' MB'],
    ['label' => '백업 폴더 용량', 'value' => number_format(safeDirSize(getBackupDir()) / 1024 / 1024, 2) . ' MB'],
    ['label' => '검색 인덱스', 'value' => number_format($searchIndexCount) . ' / ' . number_format(count($searchIndexNames))],
    ['label' => '태그 수', 'value' => number_format(safeScalarCount("SELECT COUNT(*) FROM tags"))],
    ['label' => '메모 있는 곡', 'value' => number_format(safeScalarCount("SELECT COUNT(*) FROM track_notes WHERE note_text IS NOT NULL AND TRIM(note_text) != ''"))],
];

renderHeader('성능 점검', 'performance');
?>
<div class="admin-dashboard performance-page">
    <div class="page-title-section">
        <h1 class="page-main-title">성능 점검</h1>
        <p class="page-subtitle">로그 규모, 캐시 규모, 재생 기록 등 느려질 수 있는 후보를 확인합니다.</p>
    </div>
    <?php renderStatGrid($metrics); ?>
    <section class="settings-card">
        <h2 class="section-title">권장 점검</h2>
        <p class="settings-muted">로그가 과도하게 많거나 캐시 폴더가 커진 경우 설정의 유지보수 도구에서 정리하세요. 대용량 음악 목록은 기본 표시 개수 설정과 더보기 구조를 유지하는 것이 좋습니다.</p>
    </section>
</div>
<?php renderFooter(); ?>
