import os
import sys
import time
from threading import Lock

from flask import Flask, jsonify
from core.config import SECRET_KEY
from core.db import init_db, close_db
from routes.auth_routes import auth_bp
from routes.dashboard_routes import dashboard_bp
from routes.customer_routes import customer_bp
from routes.product_routes import product_bp
from routes.sales_routes import sales_bp
from routes.stock_routes import stock_bp
from routes.page_routes import page_bp
from routes.module_routes import module_bp
from routes.payment_routes import payment_bp
from routes.report_routes import report_bp
from routes.settings_routes import settings_bp

BASE_DIR = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))

app = Flask(
    __name__,
    template_folder=os.path.join(BASE_DIR, "templates"),
    static_folder=os.path.join(BASE_DIR, "static")
)
app.secret_key = SECRET_KEY

app.register_blueprint(page_bp)
app.register_blueprint(module_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(dashboard_bp)
app.register_blueprint(customer_bp)
app.register_blueprint(product_bp)
app.register_blueprint(sales_bp)
app.register_blueprint(stock_bp)
app.register_blueprint(payment_bp)
app.register_blueprint(report_bp)
app.register_blueprint(settings_bp)

app.teardown_appcontext(close_db)

_browser_lock = Lock()
_last_browser_ping = 0.0
_browser_connected = False


def mark_browser_ping():
    global _last_browser_ping, _browser_connected
    with _browser_lock:
        _last_browser_ping = time.time()
        _browser_connected = True


def mark_browser_closed():
    global _browser_connected
    with _browser_lock:
        _browser_connected = False


def get_browser_state():
    with _browser_lock:
        return {
            "last_ping": _last_browser_ping,
            "connected": _browser_connected
        }


@app.route("/api/durum", methods=["GET"])
def api_durum():
    return jsonify({
        "ok": True,
        "app": "SatTakip"
    })


@app.route("/api/browser-ping", methods=["POST"])
def api_browser_ping():
    mark_browser_ping()
    return jsonify({"ok": True})


@app.route("/api/browser-close", methods=["POST"])
def api_browser_close():
    mark_browser_closed()
    return jsonify({"ok": True})


@app.route("/api/browser-state", methods=["GET"])
def api_browser_state():
    return jsonify(get_browser_state())


if __name__ == "__main__":
    init_db()
    print("=" * 50)
    print("  SatTakip")
    print("  http://localhost:5000 adresini acin")
    print("  Cikmak icin CTRL+C")
    print("=" * 50)
    app.run(debug=False, host="127.0.0.1", port=5000)