from flask import Blueprint, jsonify, request
from config import config_manager
from utils.placeholders import ServicePlaceholder, long_running_task

actions_bp = Blueprint('actions', __name__, url_prefix='/api')

@actions_bp.route('/downloader/add', methods=['POST'])
def add_download_task():
    # 逻辑: 根据配置，将下载链接添加到 qBittorrent 或 Transmission
    # 返回格式: {"message": "任务添加成功"}
    data = request.get_json()
    if not data or 'download_url' not in data:
        return jsonify({"error": "缺少 download_url"}), 400

    downloader_type = config_manager.get('downloader')
    config = config_manager.get(downloader_type)
    manager = ServicePlaceholder(config)

    success, message = manager.add_task(data['download_url'])
    if success:
        return jsonify({"message": f"任务已成功添加至 {downloader_type}"})
    else:
        return jsonify({"error": message}), 500

@actions_bp.route('/scrape', methods=['POST'])
def scrape_media():
    # 逻辑: 接收媒体路径，在后台线程中启动刮削任务
    # 返回格式 (202 Accepted): {"message": "刮削任务已加入队列..."}
    data = request.get_json()
    media_path = data.get('media_path')
    if not media_path:
        return jsonify({"error": "缺少 media_path"}), 400

    douban_config = config_manager.get('douban')
    manager = ServicePlaceholder(douban_config)
    
    # 在后台线程中执行刮削
    long_running_task(manager.scrape, media_path)
    
    # 立即返回 202 Accepted 响应
    return jsonify({"message": "刮削任务已加入队列，请稍后刷新查看结果"}), 202
