import asyncio

from quart import Blueprint, g, jsonify, request

from scribe.auth import get_current_user_id, login_required
from scribe.services import groups as group_svc
from scribe.services.notifications import notify_group_added

groups_bp = Blueprint("groups", __name__, url_prefix="/api/groups")


@groups_bp.route("", methods=["GET"])
@login_required
async def list_groups():
    uid = get_current_user_id()
    return jsonify({"groups": await group_svc.list_groups(uid)})


@groups_bp.route("", methods=["POST"])
@login_required
async def create_group():
    uid = get_current_user_id()
    data = await request.get_json()
    name = (data.get("name") or "").strip()
    if not name:
        return jsonify({"error": "Name is required"}), 400
    try:
        group = await group_svc.create_group(uid, name, data.get("description"))
    except Exception:
        return jsonify({"error": "Group name already taken"}), 409
    return jsonify(group.to_dict()), 201


@groups_bp.route("/<int:group_id>", methods=["GET"])
@login_required
async def get_group(group_id: int):
    group = await group_svc.get_group(group_id)
    if not group:
        return jsonify({"error": "Not found"}), 404
    members = await group_svc.list_members(group_id)
    return jsonify({**group.to_dict(), "members": members})


@groups_bp.route("/<int:group_id>", methods=["PATCH"])
@login_required
async def update_group(group_id: int):
    uid = get_current_user_id()
    data = await request.get_json()
    updates = {k: v for k, v in data.items() if k in ("name", "description")}
    group = await group_svc.update_group(uid, group_id, g.user.role == "admin", **updates)
    if not group:
        return jsonify({"error": "Not found or forbidden"}), 404
    return jsonify(group.to_dict())


@groups_bp.route("/<int:group_id>", methods=["DELETE"])
@login_required
async def delete_group(group_id: int):
    uid = get_current_user_id()
    deleted = await group_svc.delete_group(uid, group_id, g.user.role == "admin")
    if not deleted:
        return jsonify({"error": "Not found or forbidden"}), 404
    return jsonify({"status": "ok"})


@groups_bp.route("/<int:group_id>/members", methods=["GET"])
@login_required
async def list_members(group_id: int):
    members = await group_svc.list_members(group_id)
    return jsonify({"members": members})


@groups_bp.route("/<int:group_id>/members", methods=["POST"])
@login_required
async def add_member(group_id: int):
    uid = get_current_user_id()
    data = await request.get_json()
    target_uid = data.get("user_id")
    role = data.get("role", "member")
    if not target_uid:
        return jsonify({"error": "user_id required"}), 400
    if role not in ("owner", "member"):
        return jsonify({"error": "role must be owner or member"}), 400
    membership = await group_svc.add_member(uid, group_id, target_uid, role, g.user.role == "admin")
    if not membership:
        return jsonify({"error": "Forbidden, group not found, or user already a member"}), 403
    asyncio.create_task(notify_group_added(group_id, role, uid, target_uid))
    return jsonify(membership.to_dict()), 201


@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["PATCH"])
@login_required
async def update_member(group_id: int, target_uid: int):
    uid = get_current_user_id()
    data = await request.get_json()
    role = data.get("role")
    if role not in ("owner", "member"):
        return jsonify({"error": "role must be owner or member"}), 400
    m = await group_svc.update_member_role(uid, group_id, target_uid, role, g.user.role == "admin")
    if not m:
        return jsonify({"error": "Not found or forbidden"}), 404
    return jsonify(m.to_dict())


@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["DELETE"])
@login_required
async def remove_member(group_id: int, target_uid: int):
    uid = get_current_user_id()
    removed = await group_svc.remove_member(uid, group_id, target_uid, g.user.role == "admin")
    if not removed:
        return jsonify({"error": "Not found or forbidden"}), 404
    return jsonify({"status": "ok"})
