import enum
import threading

from flask import Blueprint, request, jsonify
from flask import current_app
from flask_babel import _


from extensions import db
from models.factory_structure_model import Machine, Parameter, ParameterDomain, ParameterValue
from Copilot.copilot_extentions import data_aq_manager
from Copilot.dataAcquisition.Collector.ExcelCollector import ExcelCollector
from services import auth_service
from services.locale_service import get_locale


copilot_app_api_bp = Blueprint("copilot_app_api", __name__)

# ============================================
# GET MACHINES
# ============================================

@copilot_app_api_bp.route("/copilot/api/software/toggle", methods=["POST"])
def toggle_software():

    app = current_app._get_current_object()

    data = request.get_json()

    running = data.get("running", False)

    if running:
        with app.app_context():
            db.session.query(ParameterValue).delete()
            db.session.commit()
        data_aq_manager.rebuild()
        data_aq_manager.start()



        print("START SOFTWARE")
    else:
        data_aq_manager.stop()
        print("STOP SOFTWARE")

    return jsonify({
        "success": True,
        "running": running
    })


@copilot_app_api_bp.route("/copilot/api/software/status", methods=["GET"])
def get_software_status():

    is_running = False
    is_running = data_aq_manager.is_running()


    return jsonify({
        "success": True,
        "running": is_running
    })


@copilot_app_api_bp.route("/copilot/api/incidents/analyze-req", methods=["POST"])
def analyze_incident():

    data = request.get_json(silent=True) or {}

    incident_id = data.get("incident_id")
    description = data.get("description", "")

    if not incident_id:
        return jsonify({
            "success": False,
            "message": _("‍آیدی رخداد یافت نشد")
        }), 400

    try:
        if not auth_service.is_logged_in():
            raise _("کاربر وارد نشده است. ")
        user = auth_service.current_user()
        res = data_aq_manager.request_incident_analysis(incident_id, description, user.id, lang=get_locale())
        
        if res:
            return jsonify({
                "success": True,
                "message": _("رخداد با موفقیت برای آنالیز ارسال شد")
            })
        else:
            return jsonify({
                "success": True,
                "message": _("رخداد مورد نظر یافت نشد")
            })


    except Exception as e:
        return jsonify({
            "success": False,
            "message": str(e)
        }), 500