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
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
""" 网易云音乐 API 服务主程序
提供网易云音乐相关 API 服务,包括:
- 歌曲信息获取
- 音乐搜索
- 歌单和专辑详情
- 音乐下载
- 健康检查
"""

import logging
import sys
import time
import traceback
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Any, Optional, Tuple
from urllib.parse import quote
from flask import Flask, request, send_file, render_template, Response

try:
    from music_api import (
        NeteaseAPI, APIException, QualityLevel,
        url_v1, name_v1, lyric_v1, search_music, 
        playlist_detail, album_detail
    )
    from cookie_manager import CookieManager, CookieException
    from music_downloader import MusicDownloader, DownloadException, AudioFormat
    # 导入原生MV功能模块
    from mv_api_native import NeteaseNativeMVAPI
    from mv_downloader_native import MVDownloaderNative
except ImportError as e:
    print(f" 导入模块失败: {e}")
    print("请确保所有依赖模块存在且可用")
    sys.exit(1)


@dataclass
class APIConfig:
    """API 配置类"""
    host: str = '0.0.0.0'
    port: int = 5000
    debug: bool = False
    downloads_dir: str = 'downloads'
    max_file_size: int = 500 * 1024 * 1024  # 500MB
    request_timeout: int = 30
    log_level: str = 'INFO'
    cors_origins: str = '*'


class APIResponse:
    """API 响应工具类"""
    
    @staticmethod
    def success(data: Any = None, message: str = 'success', status_code: int = 200) -> Tuple[Dict[str, Any], int]:
        """成功响应"""
        response = {
            'status': status_code,
            'success': True,
            'message': message
        }
        if data is not None:
            response['data'] = data
        return response, status_code
    
    @staticmethod
    def error(message: str, status_code: int = 400, error_code: str = None) -> Tuple[Dict[str, Any], int]:
        """错误响应"""
        response = {
            'status': status_code,
            'success': False,
            'message': message
        }
        if error_code:
            response['error_code'] = error_code
        return response, status_code


class MusicAPIService:
    """音乐 API 服务类"""
    
    def __init__(self, config: APIConfig):
        self.config = config
        self.logger = self._setup_logger()
        self.cookie_manager = CookieManager()
        self.netease_api = NeteaseAPI()
        self.downloader = MusicDownloader()
        
        # 初始化MV功能模块 - 使用原生架构
        self.mv_api = NeteaseNativeMVAPI()
        self.mv_downloader = None  # 延迟初始化
        self.logger.info(" 使用原生MV API架构")
        
        # 创建下载目录,使用临时目录避免权限问题
        if config.downloads_dir == 'downloads':
            import tempfile
            temp_dir = Path(tempfile.gettempdir()) / "music_api_downloads"
            self.downloads_path = temp_dir
        else:
            self.downloads_path = Path(config.downloads_dir)

        try:
            self.downloads_path.mkdir(parents=True, exist_ok=True)
        except PermissionError:
            # 如果权限不足,使用系统临时目录
            import tempfile
            temp_dir = Path(tempfile.gettempdir()) / "music_api_downloads"
            self.downloads_path = temp_dir
            self.downloads_path.mkdir(parents=True, exist_ok=True)
        
        self.logger.info(f" 音乐 API 服务初始化完成,下载目录: {self.downloads_path.absolute()}")
    
    def _setup_logger(self) -> logging.Logger:
        """设置日志记录器"""
        logger = logging.getLogger('music_api')
        logger.setLevel(getattr(logging, self.config.log_level.upper()))
        
        if not logger.handlers:
            # 控制台处理器
            console_handler = logging.StreamHandler()
            console_formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            console_handler.setFormatter(console_formatter)
            logger.addHandler(console_handler)
            
            # 文件处理器
            try:
                # 使用临时目录避免权限问题
                import tempfile
                log_dir = Path(tempfile.gettempdir()) / "music_api_logs"
                log_dir.mkdir(parents=True, exist_ok=True)
                log_file = log_dir / "music_api.log"

                file_handler = logging.FileHandler(str(log_file), encoding='utf-8')
                file_formatter = logging.Formatter(
                    '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
                )
                file_handler.setFormatter(file_formatter)
                logger.addHandler(file_handler)
            except Exception as e:
                logger.warning(f" 无法创建日志文件: {e}")
        
        return logger
    
    def _get_cookies(self) -> Dict[str, str]:
        """获取 Cookie"""
        try:
            cookie_str = self.cookie_manager.read_cookie()
            return self.cookie_manager.parse_cookie_string(cookie_str)
        except CookieException as e:
            self.logger.warning(f" 获取 Cookie 失败: {e}")
            return {}
        except Exception as e:
            self.logger.error(f"Cookie 处理异常: {e}")
            return {}
    
    def _extract_music_id(self, id_or_url: str) -> str:
        """提取音乐 ID"""
        try:
            # 处理短链接
            if '163cn.tv' in id_or_url:
                import requests
                response = requests.get(id_or_url, allow_redirects=False, timeout=10)
                id_or_url = response.headers.get('Location', id_or_url)
            
            # 处理网易云链接
            if 'music.163.com' in id_or_url:
                index = id_or_url.find('id=') + 3
                if index > 2:
                    return id_or_url[index:].split('&')[0]
            
            # 直接返回 ID
            return str(id_or_url).strip()
            
        except Exception as e:
            self.logger.error(f" 提取音乐 ID 失败: {e}")
            return str(id_or_url).strip()
    
    def _format_file_size(self, size_bytes: int) -> str:
        """格式化文件大小"""
        if size_bytes == 0:
            return "0B"
        
        units = ["B", "KB", "MB", "GB", "TB"]
        size = float(size_bytes)
        unit_index = 0
        
        while size >= 1024.0 and unit_index < len(units) - 1:
            size /= 1024.0
            unit_index += 1
        
        return f"{size:.2f}{units[unit_index]}"
    
    def _get_quality_display_name(self, quality: str) -> str:
        """获取音质显示名称"""
        quality_names = {
            'standard': "标准音质",
            'exhigh': "极高音质", 
            'lossless': "无损音质",
            'hires': "Hi-Res 音质",
            'sky': "沉浸环绕声",
            'jyeffect': "高清环绕声",
            'jymaster': "超清母带"
        }
        return quality_names.get(quality, f" 未知音质 ({quality})")
    
    def _validate_request_params(self, required_params: Dict[str, Any]) -> Optional[Tuple[Dict[str, Any], int]]:
        """验证请求参数"""
        for param_name, param_value in required_params.items():
            if not param_value:
                return APIResponse.error(f" 参数 '{param_name}' 不能为空 ", 400)
        return None
    
    def _safe_get_request_data(self) -> Dict[str, Any]:
        """安全获取请求数据"""
        try:
            if request.method == 'GET':
                return dict(request.args)
            else:
                # 优先使用 JSON 数据,然后是表单数据
                json_data = request.get_json(silent=True) or {}
                form_data = dict(request.form)
                # 合并数据,JSON 优先
                return {**form_data, **json_data}
        except Exception as e:
            self.logger.error(f" 获取请求数据失败: {e}")
            return {}


# 创建 Flask 应用和服务实例
config = APIConfig()
# 从环境变量加载配置(适配 Hugging Face Spaces)
# HOST:默认 0.0.0.0;PORT:优先读取 PORT,未设置则默认 7860(HF Spaces 会注入 PORT)
host = os.getenv('HOST', (config.host or '0.0.0.0'))
port_env = os.getenv('PORT')
try:
    port = int(port_env) if port_env else 7860
except ValueError:
    port = 7860
config.host = host
config.port = port

# 其他可选配置:DEBUG、DOWNLOADS_DIR、REQUEST_TIMEOUT、LOG_LEVEL、CORS_ORIGINS
debug_env = os.getenv('DEBUG')
if debug_env is not None:
    config.debug = debug_env.lower() in ('1', 'true', 'yes', 'on')

downloads_dir = os.getenv('DOWNLOADS_DIR')
if downloads_dir:
    config.downloads_dir = downloads_dir

req_timeout = os.getenv('REQUEST_TIMEOUT')
if req_timeout:
    try:
        config.request_timeout = int(req_timeout)
    except ValueError:
        pass

log_level = os.getenv('LOG_LEVEL')
if log_level:
    config.log_level = log_level

cors_origins = os.getenv('CORS_ORIGINS')
if cors_origins:
    config.cors_origins = cors_origins

app = Flask(__name__)
api_service = MusicAPIService(config)


@app.before_request
def before_request():
    """请求前处理"""
    # 记录请求信息
    api_service.logger.info(
        f"{request.method} {request.path} - IP: {request.remote_addr} - "
        f"User-Agent: {request.headers.get('User-Agent', 'Unknown')}"
    )


@app.after_request
def after_request(response: Response) -> Response:
    """请求后处理 - 设置 CORS 头"""
    response.headers.add('Access-Control-Allow-Origin', config.cors_origins)
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
    response.headers.add('Access-Control-Max-Age', '3600')
    
    # 记录响应信息
    api_service.logger.info(f" 响应状态: {response.status_code}")
    return response


@app.errorhandler(400)
def handle_bad_request(e):
    """处理 400 错误"""
    return APIResponse.error("请求参数错误", 400)


@app.errorhandler(404)
def handle_not_found(e):
    """处理 404 错误"""
    return APIResponse.error("请求的资源不存在", 404)


@app.errorhandler(500)
def handle_internal_error(e):
    """处理 500 错误"""
    api_service.logger.error(f" 服务器内部错误: {e}")
    return APIResponse.error("服务器内部错误", 500)


@app.route('/')
def index() -> str:
    """首页路由"""
    return render_template('index.html')


@app.route('/health', methods=['GET'])
def health_check():
    """健康检查 API"""
    try:
        # 检查 Cookie 状态
        cookie_status = api_service.cookie_manager.is_cookie_valid()
        
        # MV API状态
        mv_api_status = 'native'
        
        health_info = {
            'service': 'running',
            'timestamp': int(time.time()) if 'time' in sys.modules else None,
            'cookie_status': 'valid' if cookie_status else 'invalid',
            'downloads_dir': str(api_service.downloads_path.absolute()),
            'mv_api_mode': mv_api_status,
            'version': '2.1.0'
        }
        
        return APIResponse.success(health_info, "API 服务运行正常")
        
    except Exception as e:
        api_service.logger.error(f" 健康检查失败: {e}")
        return APIResponse.error(f" 健康检查失败: {str(e)}", 500)


@app.route('/song', methods=['GET', 'POST'])
@app.route('/Song_V1', methods=['GET', 'POST'])  # 向后兼容
def get_song_info():
    """获取歌曲信息 API"""
    try:
        # 获取请求参数
        data = api_service._safe_get_request_data()
        song_ids = data.get('ids') or data.get('id')
        url = data.get('url')
        level = data.get('level', 'lossless')
        info_type = data.get('type', 'url')
        
        # 参数验证
        if not song_ids and not url:
            return APIResponse.error("必须提供 'ids'、'id' 或 'url' 参数")
        
        # 提取音乐 ID
        music_id = api_service._extract_music_id(song_ids or url)
        
        # 验证音质参数
        valid_levels = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
        if level not in valid_levels:
            return APIResponse.error(f" 无效的音质参数,支持: {', '.join(valid_levels)}")
        
        # 验证类型参数
        valid_types = ['url', 'name', 'lyric', 'json']
        if info_type not in valid_types:
            return APIResponse.error(f" 无效的类型参数,支持: {', '.join(valid_types)}")
        
        cookies = api_service._get_cookies()
        
        # 根据类型获取不同信息
        if info_type == 'url':
            result = url_v1(music_id, level, cookies)
            if result and result.get('data') and len(result['data']) > 0:
                song_data = result['data'][0]
                response_data = {
                    'id': song_data.get('id'),
                    'url': song_data.get('url'),
                    'level': song_data.get('level'),
                    'quality_name': api_service._get_quality_display_name(song_data.get('level', level)),
                    'size': song_data.get('size'),
                    'size_formatted': api_service._format_file_size(song_data.get('size', 0)),
                    'type': song_data.get('type'),
                    'bitrate': song_data.get('br')
                }
                return APIResponse.success(response_data, "获取歌曲 URL 成功")
            else:
                return APIResponse.error("获取音乐 URL 失败,可能是版权限制或音质不支持", 404)
        
        elif info_type == 'name':
            result = name_v1(music_id)
            return APIResponse.success(result, "获取歌曲信息成功")
        
        elif info_type == 'lyric':
            result = lyric_v1(music_id, cookies)
            return APIResponse.success(result, "获取歌词成功")
        
        elif info_type == 'json':
            # 获取完整的歌曲信息(用于前端解析)
            song_info = name_v1(music_id)
            url_info = url_v1(music_id, level, cookies)
            lyric_info = lyric_v1(music_id, cookies)
            
            if not song_info or 'songs' not in song_info or not song_info['songs']:
                return APIResponse.error("未找到歌曲信息", 404)
            
            song_data = song_info['songs'][0]
            
            # 构建前端期望的响应格式
            response_data = {
                'id': music_id,
                'name': song_data.get('name', ''),
                'ar_name': ', '.join(artist['name'] for artist in song_data.get('ar', [])),
                'al_name': song_data.get('al', {}).get('name', ''),
                'pic': song_data.get('al', {}).get('picUrl', ''),
                'level': level,
                'lyric': lyric_info.get('lrc', {}).get('lyric', '') if lyric_info else '',
                'tlyric': lyric_info.get('tlyric', {}).get('lyric', '') if lyric_info else ''
            }
            
            # 添加 URL 和大小信息
            if url_info and url_info.get('data') and len(url_info['data']) > 0:
                url_data = url_info['data'][0]
                response_data.update({
                    'url': url_data.get('url', ''),
                    'size': api_service._format_file_size(url_data.get('size', 0)),
                    'level': url_data.get('level', level)
                })
            else:
                response_data.update({
                    'url': '',
                    'size': '获取失败'
                })
            
            return APIResponse.success(response_data, "获取歌曲信息成功")
            
    except APIException as e:
        api_service.logger.error(f"API 调用失败: {e}")
        return APIResponse.error(f"API 调用失败: {str(e)}", 500)
    except Exception as e:
        api_service.logger.error(f" 获取歌曲信息异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f" 服务器错误: {str(e)}", 500)


@app.route('/search', methods=['GET', 'POST'])
@app.route('/Search', methods=['GET', 'POST'])  # 向后兼容
def search_music_api():
    """搜索音乐 API"""
    try:
        # 获取请求参数
        data = api_service._safe_get_request_data()
        keyword = data.get('keyword') or data.get('keywords') or data.get('q')
        limit = int(data.get('limit', 30))
        offset = int(data.get('offset', 0))
        search_type = data.get('type', '1')  # 1 - 歌曲, 10 - 专辑, 100 - 歌手, 1000 - 歌单
        
        # 参数验证
        validation_error = api_service._validate_request_params({'keyword': keyword})
        if validation_error:
            return validation_error
        
        # 限制搜索数量
        if limit > 100:
            limit = 100
        
        cookies = api_service._get_cookies()
        result = search_music(keyword, cookies, limit)
        
        # search_music 返回的是歌曲列表,需要包装成前端期望的格式
        if result:
            for song in result:
                # 添加艺术家字符串(如果需要)
                if 'artists' in song:
                    song['artist_string'] = song['artists']
        
        return APIResponse.success(result, "搜索完成")
        
    except ValueError as e:
        return APIResponse.error(f" 参数格式错误: {str(e)}")
    except Exception as e:
        api_service.logger.error(f" 搜索音乐异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f" 搜索失败: {str(e)}", 500)


@app.route('/playlist', methods=['GET', 'POST'])
@app.route('/Playlist', methods=['GET', 'POST'])  # 向后兼容
def get_playlist():
    """获取歌单详情 API"""
    try:
        # 获取请求参数
        data = api_service._safe_get_request_data()
        playlist_id = data.get('id')
        
        # 参数验证
        validation_error = api_service._validate_request_params({'playlist_id': playlist_id})
        if validation_error:
            return validation_error
        
        cookies = api_service._get_cookies()
        result = playlist_detail(playlist_id, cookies)
        
        # 适配前端期望的响应格式
        response_data = {
            'status': 'success',
            'playlist': result
        }
        
        return APIResponse.success(response_data, "获取歌单详情成功")
        
    except Exception as e:
        api_service.logger.error(f" 获取歌单异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f" 获取歌单失败: {str(e)}", 500)


@app.route('/album', methods=['GET', 'POST'])
@app.route('/Album', methods=['GET', 'POST'])  # 向后兼容
def get_album():
    """获取专辑详情 API"""
    try:
        # 获取请求参数
        data = api_service._safe_get_request_data()
        album_id = data.get('id')
        
        # 参数验证
        validation_error = api_service._validate_request_params({'album_id': album_id})
        if validation_error:
            return validation_error
        
        cookies = api_service._get_cookies()
        result = album_detail(album_id, cookies)
        
        # 适配前端期望的响应格式
        response_data = {
            'status': 200,
            'album': result
        }
        
        return APIResponse.success(response_data, "获取专辑详情成功")
        
    except Exception as e:
        api_service.logger.error(f" 获取专辑异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f" 获取专辑失败: {str(e)}", 500)


@app.route('/download', methods=['GET', 'POST'])
@app.route('/Download', methods=['GET', 'POST'])  # 向后兼容
def download_music_api():
    """下载音乐 API"""
    try:
        # 获取请求参数
        data = api_service._safe_get_request_data()
        music_id = data.get('id')
        quality = data.get('quality', 'lossless')
        return_format = data.get('format', 'file')  # file 或 json
        
        # 参数验证
        validation_error = api_service._validate_request_params({'music_id': music_id})
        if validation_error:
            return validation_error
        
        # 验证音质参数
        valid_qualities = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
        if quality not in valid_qualities:
            return APIResponse.error(f" 无效的音质参数,支持: {', '.join(valid_qualities)}")
        
        # 验证返回格式
        if return_format not in ['file', 'json']:
            return APIResponse.error("返回格式只支持 'file' 或 'json'")
        
        music_id = api_service._extract_music_id(music_id)
        cookies = api_service._get_cookies()
        
        # 获取音乐基本信息
        song_info = name_v1(music_id)
        if not song_info or 'songs' not in song_info or not song_info['songs']:
            return APIResponse.error("未找到音乐信息", 404)
        
        # 获取音乐下载链接
        url_info = url_v1(music_id, quality, cookies)
        if not url_info or 'data' not in url_info or not url_info['data'] or not url_info['data'][0].get('url'):
            return APIResponse.error("无法获取音乐下载链接,可能是版权限制或音质不支持", 404)
        
        # 构建音乐信息
        song_data = song_info['songs'][0]
        url_data = url_info['data'][0]
        
        music_info = {
            'id': music_id,
            'name': song_data['name'],
            'artist_string': ', '.join(artist['name'] for artist in song_data['ar']),
            'album': song_data['al']['name'],
            'pic_url': song_data['al']['picUrl'],
            'file_type': url_data['type'],
            'file_size': url_data['size'],
            'duration': song_data.get('dt', 0),
            'download_url': url_data['url']
        }
        
        # 生成安全文件名
        safe_name = f"{music_info['name']} [{quality}]"
        
        # 如果请求JSON格式,直接返回下载信息
        if return_format == 'json':
            return APIResponse.success(music_info, "获取下载信息成功")
        
        # 执行文件下载
        try:
            from audio_format import AudioFormat
            format_map = {
                'mp3': AudioFormat.MP3,
                'flac': AudioFormat.FLAC,
                'm4a': AudioFormat.M4A
            }
            
            audio_format = format_map.get(url_data['type'].lower(), AudioFormat.MP3)
            
            # 使用下载器下载文件
            download_result = api_service.downloader.download_music(
                url=music_info['download_url'],
                filename=safe_name,
                output_dir=str(api_service.downloads_path),
                music_info=music_info,
                cookies=cookies,
                audio_format=audio_format
            )
            
            if download_result.success:
                return send_file(
                    download_result.file_path,
                    as_attachment=True,
                    download_name=Path(download_result.file_path).name,
                    mimetype='application/octet-stream'
                )
            else:
                return APIResponse.error(f"下载失败: {download_result.error_message}", 500)
                
        except Exception as e:
            api_service.logger.error(f" 下载音乐异常: {e}")
            return APIResponse.error(f" 下载失败: {str(e)}", 500)
            
    except Exception as e:
        api_service.logger.error(f" 下载音乐API异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f" 下载失败: {str(e)}", 500)


# ========== MV 相关 API ========== 

@app.route('/mv/search', methods=['GET', 'POST'])
def search_mv_api():
    """MV搜索 API"""
    try:
        data = api_service._safe_get_request_data()
        keywords = data.get('keywords') or data.get('keyword') or data.get('q')
        limit = int(data.get('limit', 30))
        offset = int(data.get('offset', 0))
        
        if not keywords:
            return APIResponse.error("必须提供搜索关键词")
        
        if limit > 100:
            limit = 100
            
        cookies = api_service._get_cookies()
        results = api_service.mv_api.search_mv(keywords, cookies, limit, offset)
        
        return APIResponse.success(results, "MV搜索完成")
        
    except Exception as e:
        api_service.logger.error(f"MV搜索异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f"MV搜索失败: {str(e)}", 500)


@app.route('/mv/detail', methods=['GET', 'POST'])
def get_mv_detail_api():
    """获取MV详情 API"""
    try:
        data = api_service._safe_get_request_data()
        mv_id = data.get('id')
        
        if not mv_id:
            return APIResponse.error("必须提供MV ID")
        
        try:
            mv_id = int(mv_id)
        except ValueError:
            return APIResponse.error("MV ID必须为数字")
            
        cookies = api_service._get_cookies()
        
        # 获取MV详情
        mv_info = api_service.mv_api.get_mv_detail(mv_id, cookies)
        # 转换为字典格式
        result = {
            'id': mv_info.id,
            'name': mv_info.name,
            'artistName': mv_info.artist,
            'artistId': mv_info.artist_id,
            'duration': mv_info.duration,
            'publishTime': mv_info.publish_time,
            'playCount': mv_info.play_count,
            'likeCount': mv_info.like_count,
            'shareCount': mv_info.share_count,
            'commentCount': mv_info.comment_count,
            'cover': mv_info.cover_url,
            'desc': mv_info.description,
            'tags': mv_info.tags or []
        }
        
        return APIResponse.success(result, "获取MV详情成功")
        
    except Exception as e:
        api_service.logger.error(f"获取MV详情异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f"获取MV详情失败: {str(e)}", 500)


@app.route('/mv/url', methods=['GET', 'POST'])
def get_mv_url_api():
    """获取MV播放链接 API"""
    try:
        data = api_service._safe_get_request_data()
        mv_id = data.get('id')
        quality = data.get('quality', '720')
        
        if not mv_id:
            return APIResponse.error("必须提供MV ID")
        
        try:
            mv_id = int(mv_id)
        except ValueError:
            return APIResponse.error("MV ID必须为数字")
            
        # 验证画质参数
        valid_qualities = ['240', '480', '720', '1080']
        if quality not in valid_qualities:
            return APIResponse.error(f"无效的画质参数,支持: {', '.join(valid_qualities)}")
            
        cookies = api_service._get_cookies()
        
        # 获取MV播放链接
        url_infos = api_service.mv_api.get_mv_url(mv_id, quality, cookies)
        # 转换为统一格式
        result = []
        for url_info in url_infos:
            result.append({
                'id': url_info.id,
                'quality': url_info.quality,
                'url': url_info.url,
                'size': url_info.size,
                'bitrate': url_info.bitrate
            })
        
        return APIResponse.success(result, "获取MV播放链接成功")
        
    except Exception as e:
        api_service.logger.error(f"获取MV播放链接异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f"获取MV播放链接失败: {str(e)}", 500)


@app.route('/mv/comment', methods=['GET', 'POST'])
def get_mv_comments_api():
    """获取MV评论 API"""
    try:
        data = api_service._safe_get_request_data()
        mv_id = data.get('id')
        limit = int(data.get('limit', 20))
        offset = int(data.get('offset', 0))
        
        if not mv_id:
            return APIResponse.error("必须提供MV ID")
        
        try:
            mv_id = int(mv_id)
        except ValueError:
            return APIResponse.error("MV ID必须为数字")
            
        if limit > 100:
            limit = 100
            
        cookies = api_service._get_cookies()
        result = api_service.mv_api.get_mv_comments(mv_id, limit, offset, cookies)
        
        return APIResponse.success(result, "获取MV评论成功")
        
    except Exception as e:
        api_service.logger.error(f"获取MV评论异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f"获取MV评论失败: {str(e)}", 500)


@app.route('/mv/download', methods=['GET', 'POST'])
def download_mv_api():
    """MV下载 API"""
    try:
        data = api_service._safe_get_request_data()
        mv_id = data.get('id')
        quality = data.get('quality', '720')
        return_format = data.get('format', 'json')  # json 或 file
        
        if not mv_id:
            return APIResponse.error("必须提供MV ID")
        
        try:
            mv_id = int(mv_id)
        except ValueError:
            return APIResponse.error("MV ID必须为数字")
            
        # 验证画质参数
        valid_qualities = ['240', '480', '720', '1080']
        if quality not in valid_qualities:
            return APIResponse.error(f"无效的画质参数,支持: {', '.join(valid_qualities)}")
            
        cookies = api_service._get_cookies()
        
        # 1. 获取MV详情
        mv_info = api_service.mv_api.get_mv_detail(mv_id, cookies)
        
        # 2. 获取下载链接
        url_infos = api_service.mv_api.get_mv_url(mv_id, quality, cookies)
        if not url_infos:
            return APIResponse.error("无法获取MV下载链接", 404)
        
        # 选择最佳画质
        selected_url = None
        for url_info in url_infos:
            if url_info.quality == quality:
                selected_url = url_info
                break
        
        if not selected_url:
            selected_url = url_infos[0]  # 使用第一个可用画质
        
        result = {
            'id': mv_id,
            'name': mv_info.name,
            'artist': mv_info.artist,
            'quality': selected_url.quality,
            'url': selected_url.url,
            'size': selected_url.size,
            'size_formatted': api_service._format_file_size(selected_url.size)
        }
        
        if return_format == 'json':
            return APIResponse.success(result, "获取MV下载信息成功")
        
        # 暂不支持直接文件下载(需要实现异步下载)
        return APIResponse.error("MV文件下载功能开发中,请使用返回的URL自行下载", 501)
        
    except Exception as e:
        api_service.logger.error(f"MV下载异常: {e}\n{traceback.format_exc()}")
        return APIResponse.error(f"MV下载失败: {str(e)}", 500)


@app.route('/api/info', methods=['GET'])
def api_info():
    """API 信息接口"""
    try:
        info = {
            'name': ' 网易云音乐 API 服务',
            'version': '2.0.0',
            'description': ' 提供网易云音乐相关 API 服务',
            'endpoints': {
                '/health': 'GET - 健康检查',
                '/song': 'GET / POST - 获取歌曲信息',
                '/search': 'GET / POST - 搜索音乐',
                '/playlist': 'GET / POST - 获取歌单详情',
                '/album': 'GET / POST - 获取专辑详情',
                '/download': 'GET / POST - 下载音乐',
                '/mv': 'GET / POST - 获取MV信息',
                '/mv/search': 'GET / POST - 搜索MV',
                '/mv/download': 'GET / POST - 下载MV',
                '/api/info': 'GET - API 信息'
            },
            'supported_qualities': [
                'standard', 'exhigh', 'lossless', 
                'hires', 'sky', 'jyeffect', 'jymaster'
            ],
            'config': {
                'downloads_dir': str(api_service.downloads_path.absolute()),
                'max_file_size': f"{config.max_file_size // (1024*1024)}MB",
                'request_timeout': f"{config.request_timeout}s"
            }
        }
        
        return APIResponse.success(info, "API 信息获取成功")
        
    except Exception as e:
        api_service.logger.error(f" 获取 API 信息异常: {e}")
        return APIResponse.error(f" 获取 API 信息失败: {str(e)}", 500)


def start_api_server():
    """启动 API 服务器"""
    try:
        print("\n" + "="*60)
        print("🚀 网易云音乐 API 服务启动中...")
        print("="*60)
        print(f"📡 服务地址: http://{config.host}:{config.port}")
        print(f"📁 下载目录: {api_service.downloads_path.absolute()}")
        print(f"📋 日志级别: {config.log_level}")
        print("\n📚 API 端点:")
        print(f"├─ GET  /health        - 健康检查")
        print(f"├─ POST /song          - 获取歌曲信息")
        print(f"├─ POST /search        - 搜索音乐")
        print(f"├─ POST /playlist      - 获取歌单详情")
        print(f"├─ POST /album         - 获取专辑详情")
        print(f"├─ POST /download      - 下载音乐")
        print(f"├─ POST /mv            - 获取MV信息")
        print(f"├─ POST /mv/search     - 搜索MV")
        print(f"├─ POST /mv/download   - 下载MV")
        print("└─ GET  /api/info      - API 信息")
        print("\n🎵 支持的音质:")
        print(f"  standard, exhigh, lossless, hires, sky, jyeffect, jymaster")
        print("\n🎥 支持的MV画质:")
        print(f"  240P, 480P, 720P, 1080P")
        print("="*60)
        print(f"⏰ 启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print("🌟 服务已就绪,等待请求...\n")
        
        # 启动 Flask 应用
        app.run(
            host=config.host,
            port=config.port,
            debug=config.debug,
            threaded=True
        )
        
    except KeyboardInterrupt:
        print("\n\n👋 服务已停止")
    except Exception as e:
        api_service.logger.error(f" 启动服务失败: {e}")
        print(f"❌ 启动失败: {e}")
        sys.exit(1)


if __name__ == '__main__':
    start_api_server()