from flask import Blueprint, jsonify, request

from hiveos.api.context import (
    authorize_core_action,
    emit_action_applied,
    emit_action_failed,
    get_core_from_request,
)


tasks_bp = Blueprint("tasks", __name__)


@tasks_bp.route("/reinject_task", methods=["POST"])
def reinject_task():
    action = "tasks.reinject"
    data = request.get_json()
    task_id = data.get("task_id")
    try:
        core = authorize_core_action(action, resource_type="task", resource_id=task_id)
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    task = core.task_objects.get(task_id)
    if not task:
        emit_action_failed(action, resource_type="task", resource_id=task_id, reason="task_not_found")
        return jsonify({"error": f"No task found with ID {task_id}"}), 404

    cloned_yaml = {
        "task_name": f"{task.name}_clone",
        "execution_mode": task.execution_mode,
        "capability_required": task.capabilities,
        "chunks": [],
    }

    for chunk in core.chunk_objects.values():
        if chunk.task_id == task_id:
            d = chunk.to_dict()
            d["chunk_id"] = d["chunk_id"].replace(f"_{task_id}", "")
            if d.get("depends_on"):
                d["depends_on"] = d["depends_on"].replace(f"_{task_id}", "")
            cloned_yaml["chunks"].append(d)

    new_task_id = core.ingest_intent(cloned_yaml)
    emit_action_applied(
        action,
        resource_type="task",
        resource_id=task_id,
        payload={"new_task_id": new_task_id},
    )
    return jsonify({"status": "reinjected", "new_task_id": new_task_id}), 200


@tasks_bp.route("/delete_task", methods=["POST"])
def delete_task():
    action = "tasks.delete"
    data = request.get_json()
    task_id = data.get("task_id")
    try:
        core = authorize_core_action(action, resource_type="task", resource_id=task_id)
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    if task_id in core.task_objects:
        core.remove_task(task_id)
        emit_action_applied(action, resource_type="task", resource_id=task_id)
        return jsonify({"status": "deleted"}), 200

    emit_action_failed(action, resource_type="task", resource_id=task_id, reason="task_not_found")
    return jsonify({"error": "Task not found"}), 404


@tasks_bp.route("/get_task_yaml", methods=["POST"])
def get_task_yaml():
    try:
        core = get_core_from_request()
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403
    data = request.get_json()
    task_id = data.get("task_id")

    task = core.task_objects.get(task_id)
    if not task:
        return jsonify({"error": f"No task found with ID {task_id}"}), 404

    chunks = [chunk.to_dict() for chunk in core.chunk_objects.values() if chunk.task_id == task_id]
    for chunk in chunks:
        chunk["chunk_id"] = chunk["chunk_id"].replace(f"_{task_id}", "")
        if chunk.get("depends_on"):
            chunk["depends_on"] = chunk["depends_on"].replace(f"_{task_id}", "")

    task_yaml = {
        "task_name": task.name,
        "execution_mode": task.execution_mode,
        "capability_required": task.capabilities,
        "chunks": chunks,
    }
    return jsonify({"yaml": task_yaml})
