import sys
sys.path.append('/workspace')
from flask import Blueprint, request, jsonify
from models.models import Client, ClientGroup
from database import Session

clients_bp = Blueprint("clients", __name__, url_prefix="/api/clients")


@clients_bp.route("", methods=["GET"])
def get_clients():
    session = Session()
    clients = session.query(Client).all()
    result = [
        {
            "uuid": c.uuid,
            "location": c.location,
            "hardware_hash": c.hardware_hash,
            "ip_address": c.ip_address,
            "last_alive": c.last_alive.isoformat() if c.last_alive else None,
            "group_id": c.group_id,
        }
        for c in clients
    ]
    session.close()
    return jsonify(result)


@clients_bp.route("/group", methods=["PUT"])
def update_clients_group():
    data = request.get_json()
    client_ids = data.get("client_ids", [])
    group_name = data.get("group_name")
    session = Session()
    group = session.query(ClientGroup).filter_by(name=group_name).first()
    if not group:
        session.close()
        return jsonify({"error": "Gruppe nicht gefunden"}), 404
    session.query(Client).filter(Client.uuid.in_(client_ids)).update(
        {Client.group_id: group.id}, synchronize_session=False
    )
    session.commit()
    session.close()
    return jsonify({"success": True})
