from datetime import datetime

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

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"
    ]

    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


@dashboard_app.route("/api/third/usage/latest", methods=["GET"])
def third_usage_latest():
    latest_rows = bh_utils.query_data("""
        select sync_time
        from geo_third_usage_snapshot
        where sync_time is not null and sync_time != ''
        order by sync_time desc
        limit 1
    """)

    if latest_rows is None:
        return jsonify({
            "code": 500,
            "msg": "query latest sync_time failed",
            "data": []
        }), 500

    if not latest_rows:
        return jsonify({
            "code": 200,
            "msg": "ok",
            "sync_time": "",
            "data": []
        })

    sync_time = latest_rows[0].get("sync_time")
    data = bh_utils.query_data("""
        select channel, pt, daily_limit, total_limit, today_used, total_used,
               today_remain, total_remain, sync_time, insertime
        from geo_third_usage_snapshot
        where sync_time = %s
        order by channel asc
    """, (sync_time,))

    if data is None:
        return jsonify({
            "code": 500,
            "msg": "query third usage snapshot failed",
            "sync_time": sync_time,
            "data": []
        }), 500

    return jsonify({
        "code": 200,
        "msg": "ok",
        "sync_time": sync_time,
        "data": data
    })


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}"
