<?php
header('Content-Type: application/json; charset=utf-8');

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/api.php';

ini_set('display_errors', 0);

$limit = max(3, min(12, (int)($_GET['limit'] ?? 8)));

try {
    $sections = getPersonalizedRecommendationSections48($limit);
    $todaySongs = getTodayRecommendationSongs16(min(8, $limit));
    $payloadSections = [];
    $flatSongs = [];
    $seen = [];
    $todayPayload = [];

    foreach ($todaySongs as $song) {
        $songPayload = apiSongPublicPayload($song);
        $songPayload['recommend_reason'] = ensureUtf8String($song['recommend_reason'] ?? '');
        $songPayload['user_rating'] = (int)($song['user_rating'] ?? 0);
        $songPayload['has_note'] = !empty($song['has_note']) ? 1 : 0;
        $todayPayload[] = $songPayload;
    }

    foreach ($sections as $section) {
        $songs = [];
        foreach ($section['songs'] as $song) {
            $songPayload = apiSongPublicPayload($song);
            $songPayload['recommend_reason'] = ensureUtf8String($song['recommend_reason'] ?? '');
            $songPayload['user_rating'] = (int)($song['user_rating'] ?? 0);
            $songPayload['has_note'] = !empty($song['has_note']) ? 1 : 0;
            $songs[] = $songPayload;

            $id = (int)($songPayload['id'] ?? 0);
            if ($id > 0 && !isset($seen[$id])) {
                $seen[$id] = true;
                $flatSongs[] = $songPayload;
            }
        }
        $payloadSections[] = [
            'key' => ensureUtf8String($section['key'] ?? ''),
            'title' => ensureUtf8String($section['title'] ?? ''),
            'description' => ensureUtf8String($section['description'] ?? ''),
            'more_url' => ensureUtf8String($section['more_url'] ?? ''),
            'count' => count($songs),
            'songs' => $songs,
        ];
    }

    apiSuccess([
        'today' => $todayPayload,
        'sections' => $payloadSections,
        'songs' => $flatSongs,
    ], '', [
        'limit' => $limit,
        'today_count' => count($todayPayload),
        'section_count' => count($payloadSections),
        'song_count' => count($flatSongs),
        'cache_policy' => 'no-store',
    ], [
        'today' => $todayPayload,
        'sections' => $payloadSections,
        'songs' => $flatSongs,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'recommendations_api_error', 'Recommendations API failed', ['error' => $e->getMessage()]);
    }
    apiError('추천 목록을 불러오지 못했습니다.', 'server_error', 500);
}
