<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';

ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

try {
    $query = trim((string)($_GET['q'] ?? ''));
    if ($query === '') {
        jsonResponse(['success' => true, 'query' => '', 'songs' => []]);
        exit;
    }
    $songs = fetchSearchSongs($query, getListDefaultLimit());
    jsonResponse(['success' => true, 'query' => ensureUtf8String($query), 'songs' => $songs]);
} catch (Exception $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search API failed', ['error' => $e->getMessage()]);
    jsonResponse(['success' => false, 'message' => '검색 결과를 불러오지 못했습니다.'], 500);
}
