from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required, current_user
from app import db
from .forms import SearchForm
from plugins.plant.models import Plant, Tag

bp = Blueprint('search', __name__, template_folder='templates')

@bp.route('/search', methods=['GET', 'POST'])
@login_required
def search():
    form = SearchForm()
    form.tags.choices = [(tag.id, tag.name) for tag in Tag.query.order_by(Tag.name).all()]
    results = []
    if form.validate_on_submit():
        query = db.session.query(Plant).join(PlantScientific).join(PlantCommon)
        if form.query.data:
            q = f"%{form.query.data}%"
            query = query.filter(
                db.or_(
                    PlantScientific.name.ilike(q),
                    PlantCommon.name.ilike(q),
                    Plant.current_status.ilike(q)
                )
            )
        if form.tags.data:
            query = query.filter(Plant.tags.any(Tag.id.in_(form.tags.data)))
        query = query.filter(Plant.owner_id == current_user.id)
        results = query.all()
    return render_template('search/search.html', form=form, results=results)

@bp.route('/search/tags')
@login_required
def search_tags():
    term = request.args.get('term', '')
    tags = Tag.query.filter(Tag.name.ilike(f"%{term}%")).limit(10).all()
    return jsonify([tag.name for tag in tags])