from quart import Blueprint, jsonify, request

from scribe.auth import get_current_user_id, login_required
from scribe.services.user_profile import (
    VALID_EXPERTISE,
    VALID_STYLES,
    VALID_TONES,
    get_profile,
    update_profile,
)

profile_bp = Blueprint("profile", __name__, url_prefix="/api/profile")


@profile_bp.route("", methods=["GET"])
@login_required
async def get_profile_route():
    uid = get_current_user_id()
    profile = await get_profile(uid)
    return jsonify(profile.to_dict())


@profile_bp.route("", methods=["PUT"])
@login_required
async def update_profile_route():
    uid = get_current_user_id()
    data = await request.get_json()
    if not isinstance(data, dict):
        return jsonify({"error": "Expected a JSON object"}), 400

    if "expertise_level" in data and data["expertise_level"] not in VALID_EXPERTISE:
        return jsonify({"error": f"expertise_level must be one of {sorted(VALID_EXPERTISE)}"}), 400
    if "response_style" in data and data["response_style"] not in VALID_STYLES:
        return jsonify({"error": f"response_style must be one of {sorted(VALID_STYLES)}"}), 400
    if "tone" in data and data["tone"] not in VALID_TONES:
        return jsonify({"error": f"tone must be one of {sorted(VALID_TONES)}"}), 400
    if "interests" in data and not isinstance(data["interests"], list):
        return jsonify({"error": "interests must be an array"}), 400
    if "work_schedule" in data and not isinstance(data["work_schedule"], dict):
        return jsonify({"error": "work_schedule must be an object"}), 400

    profile = await update_profile(uid, data)
    return jsonify(profile.to_dict())
