from flask import Blueprint, jsonify, request

from hiveos.api.context import authorize_user_action, emit_action_applied, emit_action_failed
from hiveos.session_manager import session_manager


sessions_bp = Blueprint("sessions", __name__)


@sessions_bp.route("/create_session", methods=["POST"])
def create_session():
    action = "sessions.create"
    label = request.json.get("label", None)
    user_id = request.headers.get("X-User-ID") or request.json.get("user_id")
    try:
        authorize_user_action(action, resource_type="session", user_id=user_id)
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403
    session_id = session_manager.create_session(label=label, user_id=user_id)
    emit_action_applied(
        action,
        resource_type="session",
        resource_id=session_id,
        user_id=user_id,
        session_id=session_id,
    )
    return jsonify({"session_id": session_id})


@sessions_bp.route("/switch_session", methods=["POST"])
def switch_session():
    action = "sessions.switch"
    session_id = request.json.get("session_id")
    user_id = request.headers.get("X-User-ID") or request.json.get("user_id")
    try:
        authorize_user_action(
            action,
            resource_type="session",
            user_id=user_id,
            session_id=session_id,
            resource_id=session_id,
        )
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    if session_manager.get_session_user_id(session_id) != user_id:
        emit_action_failed(
            action,
            resource_type="session",
            resource_id=session_id,
            user_id=user_id,
            session_id=session_id,
            reason="unauthorized_session_owner",
        )
        return jsonify({"error": "Unauthorized"}), 403

    if session_manager.set_active_session(session_id, user_id):
        emit_action_applied(
            action,
            resource_type="session",
            resource_id=session_id,
            user_id=user_id,
            session_id=session_id,
        )
        return jsonify({"status": "ok"})

    emit_action_failed(
        action,
        resource_type="session",
        resource_id=session_id,
        user_id=user_id,
        session_id=session_id,
        reason="invalid_session_id",
    )
    return jsonify({"error": "Invalid session ID"}), 400


@sessions_bp.route("/get_sessions", methods=["GET"])
def get_sessions():
    user_id = request.headers.get("X-User-ID") or request.args.get("user_id")
    sessions = session_manager.get_user_sessions(user_id)
    return jsonify({"sessions": sessions, "active": session_manager.active_sessions.get(user_id)})


@sessions_bp.route("/delete_session", methods=["POST"])
def delete_session():
    action = "sessions.delete"
    session_id = request.json.get("session_id")
    user_id = request.headers.get("X-User-ID") or request.json.get("user_id")
    try:
        authorize_user_action(
            action,
            resource_type="session",
            user_id=user_id,
            session_id=session_id,
            resource_id=session_id,
        )
    except PermissionError as e:
        return jsonify({"error": str(e)}), 403

    if session_manager.get_session_user_id(session_id) != user_id:
        emit_action_failed(
            action,
            resource_type="session",
            resource_id=session_id,
            user_id=user_id,
            session_id=session_id,
            reason="unauthorized_session_owner",
        )
        return jsonify({"error": "Unauthorized"}), 403

    success = session_manager.delete_session(session_id)
    if success:
        emit_action_applied(
            action,
            resource_type="session",
            resource_id=session_id,
            user_id=user_id,
            session_id=session_id,
        )
    else:
        emit_action_failed(
            action,
            resource_type="session",
            resource_id=session_id,
            user_id=user_id,
            session_id=session_id,
            reason="session_delete_failed",
        )
    return jsonify({"success": success})


@sessions_bp.route("/echo_headers", methods=["GET"])
def echo_headers():
    return jsonify(dict(request.headers))
