<?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/functions_search.php';
require_once dirname(__DIR__) . '/includes/api.php';

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

try {
    $query = normalizeSearchQuery($_GET['q'] ?? '');
    if ((function_exists('mb_strlen') ? mb_strlen($query, 'UTF-8') : strlen($query)) < 2) {
        apiSuccess(['query' => '', 'songs' => []], '', ['count' => 0], ['query' => '', 'songs' => []]);
    }

    $songs = array_map(function ($song) {
        $id = (int)($song['id'] ?? 0);
        return [
            'id' => $id,
            'song_id' => $id,
            'title' => ensureUtf8String($song['title'] ?? ''),
            'artist' => artistName($song['artist'] ?? ''),
            'album' => albumName($song['album'] ?? ''),
            'genre' => genreName($song['genre'] ?? ''),
            'duration' => (int)($song['duration'] ?? 0),
            'extension' => (string)($song['extension'] ?? ''),
            'play_count' => (int)($song['play_count'] ?? 0),
            'is_liked' => !empty($song['is_liked']) ? 1 : 0,
            'user_rating' => (int)($song['user_rating'] ?? 0),
            'has_note' => !empty($song['has_note']) ? 1 : 0,
            'cover_url' => coverUrl($song),
            'stream_url' => 'stream.php?id=' . $id,
            'song_url' => 'song.php?id=' . $id,
            'lyrics_url' => 'api/get_lyrics.php?song_id=' . $id,
        ];
    }, fetchSearchSongs($query, getListDefaultLimit()));

    apiSuccess([
        'query' => ensureUtf8String($query),
        'songs' => $songs,
    ], '', ['count' => count($songs)], [
        'query' => ensureUtf8String($query),
        'songs' => $songs,
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'search_error', 'Search API failed', ['error' => $e->getMessage()]);
    apiError('검색 결과를 불러오지 못했습니다.', 'server_error', 500);
}
