"""User settings + integrations (SearXNG status).

Chat-model picker endpoints (/models), KV-cache priming, and journal-schedule
hooks were removed in Phase 8 alongside the chat/journal subsystems.
"""
import logging

from quart import Blueprint, jsonify, request

from scribe.auth import login_required, get_current_user_id
from scribe.config import Config
from scribe.services.settings import delete_setting, get_all_settings, get_setting, set_settings_batch

logger = logging.getLogger(__name__)


settings_bp = Blueprint("settings", __name__, url_prefix="/api/settings")


@settings_bp.route("", methods=["GET"])
@login_required
async def get_settings_route():
    uid = get_current_user_id()
    settings = await get_all_settings(uid)
    return jsonify(settings)


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

    to_save = {}
    for k, v in data.items():
        str_v = str(v)
        if not str_v:
            await delete_setting(uid, k)
        else:
            to_save[k] = str_v

    if to_save:
        await set_settings_batch(uid, to_save)

    settings = await get_all_settings(uid)
    return jsonify(settings)


@settings_bp.route("/search", methods=["GET"])
@login_required
async def test_search():
    """Report SearXNG configuration status (used by the Integrations tab)."""
    if not Config.searxng_enabled():
        return jsonify({"configured": False, "results": [], "searxng_url": ""})
    return jsonify({"configured": True, "results": [], "searxng_url": Config.SEARXNG_URL})
