"""
Shop Manager POS - Desktop Launcher
------------------------------------
Runs the Flask app silently in a background thread and opens it in a
native app window (via pywebview) - no terminal window, no browser tab.

This is the entry point built into ShopManagerPOS.exe (see
ShopManagerPOS.spec). Plain `python app.py` / `python app.py` still
works the normal (browser-based) way for local development.
"""
import os
import socket
import threading
import time

# ---------------------------------------------------------------
# Gmail credentials for the "Forgot password" email feature.
# Must be set BEFORE `import app`, since config.py reads them at
# import time. In start_pos.bat these were set as environment
# variables; the packaged .exe doesn't run that .bat, so we set
# sensible defaults here. They can still be overridden by setting
# real environment variables on the machine (that takes priority
# only if you delete the os.environ.setdefault calls below).
# ---------------------------------------------------------------
os.environ.setdefault("POS_GMAIL_ADDRESS", "greenviewagro2025@gmail.com")
os.environ.setdefault("POS_GMAIL_APP_PASSWORD", "fxuiqtsedihkcwni")

import webview  # pywebview - native window, no browser chrome

from app import app, initialize_app, get_lan_ip

HOST = "0.0.0.0"
PORT = 5000


def _wait_for_server(host, port, timeout=15):
    """Poll the socket until Flask is actually accepting connections,
    so the webview window doesn't open on a blank/connection-refused
    page."""
    deadline = time.time() + timeout
    probe_host = "127.0.0.1" if host == "0.0.0.0" else host
    while time.time() < deadline:
        try:
            with socket.create_connection((probe_host, port), timeout=0.5):
                return True
        except OSError:
            time.sleep(0.2)
    return False


def _run_flask():
    # use_reloader=False is required: the reloader spawns a second
    # process, which breaks a frozen PyInstaller exe. threaded=True
    # lets the POS and phone browsers hit it at the same time.
    app.run(host=HOST, port=PORT, debug=False, use_reloader=False, threaded=True)


def main():
    try:
        initialize_app()
    except Exception as exc:
        print(f"[ERROR] Application initialization error: {exc}")
        try:
            from paths import DATA_DIR
            sqlite_uri = "sqlite:///" + os.path.join(DATA_DIR, "shop.db")
            app.config["SQLALCHEMY_DATABASE_URI"] = sqlite_uri
            initialize_app()
        except Exception as retry_exc:
            print(f"[FATAL] Fallback initialization failed: {retry_exc}")
            import sys
            import tkinter as tk
            from tkinter import messagebox
            root = tk.Tk()
            root.withdraw()
            messagebox.showerror("Shop Manager POS Error", f"Database Connection Error:\n{exc}")
            sys.exit(1)

    server_thread = threading.Thread(target=_run_flask, daemon=True)
    server_thread.start()

    _wait_for_server(HOST, PORT)

    lan_ip = get_lan_ip()
    print(f"SERVER STARTING... phone access: http://{lan_ip}:{PORT}")

    webview.create_window(
        "Shop Manager POS",
        "http://127.0.0.1:5000",
        width=1280,
        height=800,
        min_size=(1024, 700),
    )
    # Closing the window ends the process (and the daemon server thread).
    webview.start()


if __name__ == "__main__":
    main()
