from flask import Blueprint, jsonify
from config import config_manager
from utils.placeholders import ServicePlaceholder
from utils.plex_utils import PlexManager

dashboard_bp = Blueprint('dashboard', __name__, url_prefix='/api/dashboard')

@dashboard_bp.route('/initial_check', methods=['GET'])
def initial_check():
    # 逻辑: 检查配置文件中是否至少有一个关键项被配置，例如ptskit的URL
    # 返回格式: {"is_configured": true | false}
    is_configured = bool(config_manager.get('ptskit', {}).get('url'))
    return jsonify({"is_configured": is_configured})

@dashboard_bp.route('/stats', methods=['GET'])
def get_stats():
    # 逻辑: 分别连接 qBittorrent, Transmission, Emby 等服务获取它们的项目总数
    # 返回格式: {"local_skits": int, "fnos_items": int, ...}
    qb_manager = ServicePlaceholder(config_manager.get('qbittorrent'))
    plex_config = config_manager.get('plex')
    plex_manager = PlexManager(plex_config)
    plex_items = plex_manager.get_stats()
    return jsonify({
        "local_skits": 15,
        "fnos_items": 12,
        "emby_items": 12,
        "plex_items": plex_items,
        "qb_total": qb_manager.get_stats(),
        "tr_total": 4
    })

@dashboard_bp.route('/component_statuses', methods=['GET'])
def get_component_statuses():
    # 逻辑: 对每个配置的服务进行一次连接测试，并返回其状态
    # 返回格式: {"qbittorrent": {"status": "success" | "error" | "unconfigured", "message": str}, ...}
    plex_config = config_manager.get('plex')
    plex_status = {"status": "unconfigured", "message": "未配置"}
    if plex_config and plex_config.get('host'):
        plex_manager = PlexManager(plex_config)
        success, message = plex_manager.test_connection()
        plex_status = {"status": "success" if success else "error", "message": message}
    
    
    return jsonify({
        "douban_cookie": {"status": "success", "message": "Cookie已配置"},
        "ptskit_cookie": {"status": "success", "message": "Cookie已配置"},
        "local_path": {"status": "success", "message": "已挂载"},
        "qbittorrent": {"status": "success", "message": "连接成功 v4.5.2"},
        "transmission": {"status": "error", "message": "连接失败: 认证错误"},
        "fnos": {"status": "unconfigured", "message": "未配置"},
        "emby": {"status": "success", "message": "连接成功"},
        "plex": plex_status
    })
