"""Disease lookup API routes."""
import re

from flask import Blueprint, jsonify, request

from app.db import Database
from app.routes.auth import auth_required

diseases_bp = Blueprint('diseases_api', __name__)


@diseases_bp.route('/diseases', methods=['GET'])
@auth_required
def search_diseases_endpoint():
    """Search diseases by name or ICD code.
    ---
    tags:
        - Diseases
    security:
        - BearerAuth: []
    parameters:
        - in: query
          name: search
          schema:
            type: string
          description: Search term to match against disease name or ICD code
    responses:
        200:
            description: Array of matching diseases (max 20)
            content:
                application/json:
                    schema:
                        type: array
                        items:
                            type: object
                            properties:
                                _id:
                                    type: string
                                icdCode:
                                    type: string
                                name:
                                    type: string
                                bodyRegion:
                                    type: string
                                description:
                                    type: string
    """
    search = (request.args.get('search') or '').strip()
    db = Database.get_db()

    if not search:
        return jsonify([])

    escaped = re.escape(search)
    query = {
        '$or': [
            {'name': {'$regex': escaped, '$options': 'i'}},
            {'icdCode': {'$regex': escaped, '$options': 'i'}},
        ]
    }
    docs = list(db.get_collection('diseases').find(query).limit(20))

    results = []
    for doc in docs:
        results.append({
            '_id': str(doc['_id']),
            'icdCode': doc.get('icdCode', ''),
            'name': doc.get('name', ''),
            'bodyRegion': doc.get('bodyRegion', ''),
            'description': doc.get('description', ''),
        })

    return jsonify(results)
