from datetime import datetime

from flask import jsonify, Blueprint, render_template, request
import requests
from aidso_geo.config.base_config import init_redis

dashboard_app = Blueprint("dashboard", __name__)

redis_client = init_redis()


@dashboard_app.route("/api/queue/status", methods=["GET"])
def queue_status():
    data = {}

    platforms = [
        "BDAI", "DB", "DOUBA", "DP", "DPA", "DYAI",
        "KIMI", "TXYB", "TXYBA", "TYQW", "TYQWA", "WXYY", "XHSA"
    ]

    for platform in platforms:
        stream_key = f"{platform}:geo:stream_batch:list"
        batch_key = f"{platform}:geo:batch:list"

        data[stream_key] = redis_client.llen(stream_key)
        data[batch_key] = redis_client.llen(batch_key)

    data["geo:task_commit:list"] = redis_client.llen("geo:task_commit:list")

    return jsonify(data)


@dashboard_app.route("/queue/monitor", methods=["GET"])
def queue_monitor_page():
    return render_template("queue_monitor.html")


@dashboard_app.route("/api/queue/platformStats", methods=["GET"])
def get_req_trend():
    begin = request.args.get("begin", "").strip()
    end = request.args.get("end", "").strip()

    if not begin or not end:
        return jsonify({
            "code": 400,
            "msg": "begin and end are required",
            "data": []
        }), 400

    try:
        params = {
            "begin": normalize_date_to_datetime(begin, "00:00:00"),
            "end": normalize_date_to_datetime(end, "23:59:59"),
        }
        begin_time = datetime.strptime(params["begin"], "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(params["end"], "%Y-%m-%d %H:%M:%S")

        if begin_time > end_time:
            return jsonify({
                "code": 400,
                "msg": "begin must be earlier than end",
                "data": []
            }), 400
    except ValueError:
        return jsonify({
            "code": 400,
            "msg": "begin and end must be YYYY-MM-DD",
            "data": []
        }), 400

    url = "https://openapi.aidso.com/openapi/ywt/platformStats"

    try:
        response = requests.get(url, params=params, timeout=300)
        response.raise_for_status()
        return jsonify(response.json())
    except (requests.RequestException, ValueError) as e:
        return jsonify({
            "code": 500,
            "msg": f"platformStats request failed: {e}",
            "data": []
        }), 500


def normalize_date_to_datetime(value, default_time):
    date_value = value.replace("T", " ").strip()[:10]
    datetime.strptime(date_value, "%Y-%m-%d")
    return f"{date_value} {default_time}"
