<?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';

$songId = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_GET['song_id']) ? (int)$_GET['song_id'] : 0);
$includeLyrics = isset($_GET['include']) && $_GET['include'] === 'lyrics';

if ($songId <= 0) {
    apiError('올바르지 않은 곡 ID입니다.', 'invalid_song_id', 400);
}

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare(apiSongSelectSql() . "
        WHERE s.id = :id
          AND COALESCE(s.is_missing, 0) = 0
          AND COALESCE(s.is_hidden, 0) = 0
        LIMIT 1
    ");
    $stmt->execute([':id' => $songId]);
    $song = $stmt->fetch();

    if (!$song) {
        apiError('곡을 찾을 수 없습니다.', 'song_not_found', 404);
    }

    $data = apiSongPublicPayload($song, ['include_lyrics' => $includeLyrics]);
    $data['updated_at'] = ensureUtf8String($song['updated_at'] ?? '');

    apiSuccess($data);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'song_api_error', 'Song API failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    apiError('곡 정보를 불러오지 못했습니다.', 'server_error', 500);
}
