from flask import Blueprint, jsonify, request

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


intent_bp = Blueprint("intent", __name__)


@intent_bp.route("/intent_preview", methods=["POST"])
def intent_preview():
    action = "intent.preview"
    try:
        core = authorize_core_action(action, resource_type="session")
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    data = request.get_json(silent=True) or {}
    prompt = data.get("prompt")
    user_id = request.headers.get("X-User-ID")
    session_id = request.headers.get("X-Session-ID")
    scope = data.get("scope", "session")
    approval_mode = data.get("approval_mode", "review_required")
    use_model = bool(data.get("use_model", True))

    try:
        compiled = core.intent_service.compile_intent(
            prompt=prompt,
            user_id=user_id,
            session_id=session_id,
            scope=scope,
            approval_mode=approval_mode,
            use_model=use_model,
        )
        emit_action_applied(
            action,
            resource_type="session",
            payload={
                "intent_id": compiled["intent"]["intent_id"],
                "run_spec_id": compiled["run_spec"]["run_spec_id"],
            },
        )
        return jsonify(compiled), 200
    except Exception as e:
        emit_action_failed(action, resource_type="session", reason=e)
        return jsonify({"error": str(e)}), 400


@intent_bp.route("/intent_apply", methods=["POST"])
def intent_apply():
    action = "intent.apply"
    try:
        core = authorize_core_action(action, resource_type="session")
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    data = request.get_json(silent=True) or {}
    run_spec_id = data.get("run_spec_id")
    if not run_spec_id:
        return jsonify({"error": "Missing run_spec_id"}), 400

    try:
        outcome = core.intent_service.apply_run_spec(run_spec_id)
        emit_action_applied(
            action,
            resource_type="session",
            payload={"intent_id": outcome["intent_id"], "run_spec_id": run_spec_id, "status": outcome["status"]},
        )
        return jsonify({"outcome": outcome}), 200
    except KeyError:
        emit_action_failed(action, resource_type="session", reason="run_spec_not_found", payload={"run_spec_id": run_spec_id})
        return jsonify({"error": "run_spec_not_found"}), 404
    except Exception as e:
        emit_action_failed(action, resource_type="session", reason=e, payload={"run_spec_id": run_spec_id})
        return jsonify({"error": str(e)}), 500


@intent_bp.route("/intent_specs", methods=["GET"])
def intent_specs():
    try:
        core = get_core_from_request()
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403
    run_spec_id = request.args.get("run_spec_id")
    if run_spec_id:
        run_spec = core.intent_service.get_run_spec(run_spec_id)
        if not run_spec:
            return jsonify({"error": "run_spec_not_found"}), 404
        return jsonify({"run_spec": run_spec}), 200
    return jsonify({"error": "run_spec_id query param required"}), 400
