from flask import Blueprint, jsonify, request
from sqlalchemy import select
from web_application import db
from web_application.models import Hat, Sensor, SiloSistem, TitresimVerisi

api_bp = Blueprint(
    "api",
    __name__,
    url_prefix="/api",
)


@api_bp.route("/add-sensor-data", methods=["POST"])
def add_sensor_data():
    data = request.get_json()

    if not data:
        return jsonify({"error": "No data provided"}), 400

    try:
        new_entry = Sensor()

        for key, value in data.items():
            if hasattr(new_entry, key):
                setattr(new_entry, key, value)

        db.session.add(new_entry)
        db.session.commit()

        return jsonify(
            {"message": "Sensor data recorded successfully", "id": new_entry.id}
        ), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


@api_bp.route("/add-vibration-data", methods=["POST"])
def add_vibration_data():
    data = request.get_json()
    if not data:
        return jsonify({"error": "No data provided"}), 400

    try:
        new_vibration = TitresimVerisi()

        # Automatic mapping for v_rms, a_peak, a_rms, and status fields
        for key, value in data.items():
            if hasattr(new_vibration, key):
                setattr(new_vibration, key, value)

        db.session.add(new_vibration)
        db.session.commit()

        return jsonify({"message": "Vibration data saved", "id": new_vibration.id}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


@api_bp.route("/add-silo-data", methods=["POST"])
def add_silo_data():
    data = request.get_json()
    if not data:
        return jsonify({"error": "No data provided"}), 400

    try:
        new_silo_entry = SiloSistem()

        # Iterates through silo1-3, pompa1-8, chiller1-2, and environment metrics
        for key, value in data.items():
            if hasattr(new_silo_entry, key):
                setattr(new_silo_entry, key, value)

        db.session.add(new_silo_entry)
        db.session.commit()

        return jsonify(
            {"message": "Silo sistem verisi kaydedildi", "id": new_silo_entry.id}
        ), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


@api_bp.route("/bolum-hatlari/<int:bolum_id>", methods=["GET"])
def get_bolum_hatlari(bolum_id):
    try:
        from web_application.models import Hat
        sql = select(Hat).where(Hat.bolum_id == bolum_id, Hat.durum == 1)
        hatlar = db.session.execute(sql).scalars().all()
        return jsonify([{"id": h.id, "adi": h.adi} for h in hatlar])
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@api_bp.route("/last-records/<int:hat_id>", methods=["GET"])
def get_last_records(hat_id):
    try:
        # Filter by the specific hat_id and get the last 10 records
        sql_sensor = (
            select(Sensor)
            .where(Sensor.hat_id == hat_id)
            .order_by(Sensor.tarih.desc())
            .limit(10)
        )
        sensors = db.session.execute(sql_sensor).scalars().all()

        # Vibration data might not have a hat_id, if so, just get the latest
        sql_vibes = (
            select(TitresimVerisi)
            .order_by(TitresimVerisi.tarih.desc())
            .limit(10)
        )
        vibes = db.session.execute(sql_vibes).scalars().all()

        return jsonify(
            {
                "sensor": [s.to_dict() for s in reversed(list(sensors))],
                "vibration": [v.to_dict() for v in reversed(list(vibes))],
            }
        )
    except Exception as e:
        return jsonify({"error": str(e)}), 500

