import logging
from datetime import datetime, timezone

from wurker.settings import conf
from wurker import StatusCommand
from wurker.ui.auth import api_auth_required

from flask import Blueprint, g, render_template, jsonify
from werkzeug.exceptions import abort


bp = Blueprint('report', __name__)

logger = logging.getLogger('gunicorn.error')


@bp.route('/report/<slug>')
@bp.route('/report/<slug>/daterange/<start>/<end>')
@bp.route('/drone/<drone_id>/report/<slug>')
@bp.route('/drone/<drone_id>/report/<slug>/daterange/<start>/<end>')
@api_auth_required
def report(slug:str, drone_id:str='', start:str='', end:str=''):
    """View the report view this Wurker (Queen or Drone) and given Bee slug."""

    if drone_id and not conf.is_queen:
        return None, 404

    drones = [drone_id] if drone_id else []

    try:
        cmd = StatusCommand()

        queen = cmd.run(return_result=True)
        if not queen:
            return jsonify({"error": "Error obtaining status of Queen"}), 400

        status = cmd.run(drones=drones, return_result=True)

    except Exception as ex:
        return jsonify({"error": f"{ex}"}), 400

    info = (
        status if not drone_id
        else {} if not status or drone_id not in status
        else status[drone_id]
    )

    if not info:
        return jsonify({"error": f"Error obtaining status"}), 400

    # Set daterange
    daterange = {}
    if start and end:
        daterange = {"start": start, "end": end}

    # Compose the result and render it
    result = {
        "page": info.get("name", None),
        "app_id": info.get("app_id", None),
        "is_queen": info.get("is_queen", None),
        "drones": queen.get("drones", None),
        "env": info.get("env", None),
        "report_slug": slug,
        "daterange": daterange,
        "thisYear": datetime.now(timezone.utc).strftime('%Y'),   # For copyright
    }

    return render_template('report.html', **result)
