<?php
// sou_api.php

// 设置跨域请求头
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// 初始化响应数组
$response = [
    'status' => 'error',
    'message' => 'Unknown error',
    'count' => 0,
    'results' => []
];

try {
    // 1. 验证请求方法
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        http_response_code(405);
        $response['message'] = 'Method Not Allowed';
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 2. 验证并获取必要的参数
    if (!isset($_GET['action']) || $_GET['action'] !== 'getSou') {
        http_response_code(400);
        $response['message'] = 'Invalid action. Use ?action=getSou';
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 检查搜索词是否存在
    if (!isset($_GET['s'])) {
        http_response_code(400);
        $response['message'] = 'Missing search term. Use &s=your_keyword';
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    $searchTerm = trim($_GET['s']);
    
    // 如果搜索词为空，则返回空结果
    if (empty($searchTerm)) {
        $response['status'] = 'success';
        $response['message'] = 'Search term is empty, returning no results.';
        $response['count'] = 0;
        $response['results'] = [];
        http_response_code(200);
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 3. 引入音乐数据
    $musicFile = __DIR__ . '/data/music.php';
    if (!file_exists($musicFile)) {
        http_response_code(500);
        $response['message'] = 'Music data file not found at ' . $musicFile;
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 使用require确保每次都能获取最新数据
    $musicList = require $musicFile;
    
    // 验证音乐数据格式
    if (!is_array($musicList)) {
        http_response_code(500);
        $response['message'] = 'Invalid music data format in ' . $musicFile;
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 4. 定义音乐分类（用于返回更丰富的信息）
    $categories = [
        'all' => ['name' => '全部音乐', 'color' => '#b89e81', 'text_color' => '#5d4037'],
        'cantonese' => ['name' => '粤语歌曲', 'color' => '#c8e6c9', 'text_color' => '#2e7d32'],
        'mandarin' => ['name' => '国语歌曲', 'color' => '#fff3e0', 'text_color' => '#e65100'],
        'waiyu' => ['name' => '外语歌曲', 'color' => '#e3f2fd', 'text_color' => '#0d47a1'],
        'classic' => ['name' => '经典老歌', 'color' => '#efebe9', 'text_color' => '#3e2723'],
        'other' => ['name' => '其他音乐', 'color' => '#f3e5f5', 'text_color' => '#6a1b9a']
    ];

    // 5. 执行搜索
    $searchResults = [];
    $lowerTerm = strtolower($searchTerm);
    
    foreach ($musicList as $music) {
        // 检查音乐条目是否有效
        if (!is_array($music) || !isset($music['title'], $music['artist'])) {
            continue; // 跳过无效条目
        }
        
        if (strpos(strtolower($music['title']), $lowerTerm) !== false || 
            strpos(strtolower($music['artist']), $lowerTerm) !== false) {
            // 为结果添加分类信息，如果分类不存在则使用'other'
            $music['category_info'] = $categories[$music['category']] ?? $categories['other'];
            $searchResults[] = $music;
        }
    }

    // 6. 构建成功响应
    $response = [
        'status' => 'success',
        'action' => 'getSou',
        'search_term' => $searchTerm,
        'count' => count($searchResults),
        'results' => $searchResults
    ];

    http_response_code(200);
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;

} catch (Exception $e) {
    // 捕获所有未预见的异常
    http_response_code(500);
    $response['message'] = 'Server error: ' . $e->getMessage();
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}
?>