from flask import Blueprint, jsonify, request
import yaml

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


runtime_bp = Blueprint("runtime", __name__)


@runtime_bp.route("/")
def index():
    return "HiveCore API is running.", 200


@runtime_bp.route("/inject_yaml", methods=["POST"])
def inject_yaml():
    action = "runtime.inject_yaml"
    try:
        core = authorize_core_action(action, resource_type="session")
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403
    try:
        raw_yaml = request.data.decode("utf-8")
        parsed = yaml.safe_load(raw_yaml)
        task_id = core.ingest_intent(parsed)
        emit_action_applied(action, resource_type="session", payload={"task_id": task_id})
        return {"success": f"Task {task_id} injected"}, 200
    except Exception as e:
        import traceback

        traceback.print_exc()
        emit_action_failed(action, resource_type="session", reason=e)
        return {"error": str(e)}, 500


@runtime_bp.route("/status", methods=["GET"])
def status():
    try:
        core = get_core_from_request()
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    session_id = request.headers.get("X-Session-ID")
    return jsonify(build_status_response(core, session_id))
