<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/api.php';
require_once __DIR__ . '/../includes/stats_functions.php';
require_once __DIR__ . '/../includes/functions_tags.php';
require_once __DIR__ . '/../includes/functions_notes.php';

try {
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $limit = max(1, min(30, $limit));
    $songs = getAutoMixSongs17($limit);
    $tracks = array_map(function ($song) {
        $payload = apiSongPayload($song);
        if (!empty($song['recommend_reason'])) {
            $payload['recommend_reason'] = ensureUtf8String($song['recommend_reason']);
        }
        return $payload;
    }, $songs);

    apiSuccess(
        [
            'tracks' => $tracks,
            'count' => count($tracks),
        ],
        count($tracks) > 0
            ? '자동 믹스를 만들었습니다.'
            : '자동 믹스를 만들 곡이 아직 부족합니다.'
    );
} catch (Throwable $e) {
    apiHandleThrowable($e, 'SERVER_ERROR', 500, [
        'limit' => $_GET['limit'] ?? null,
    ]);
}
