"""Serve Msururu ERP to other computers on the network (production server, no debugger).

    python serve.py            # listens on all network cards, port 5000

While it runs, a backup (database + uploads) is made every night at 02:00.
"""
import os
import socket
import threading
import time
from datetime import datetime, timedelta
from waitress import serve
from app import create_app
from app.utils.net import lan_ips, port_in_use

HOST = os.environ.get("MIZANI_HOST", "0.0.0.0")
PORT = int(os.environ.get("MIZANI_PORT", "5000"))
BACKUP_HOUR = int(os.environ.get("MIZANI_BACKUP_HOUR", "2"))




def nightly_backups(app):
    from app.services import backup
    while True:
        now = datetime.now()
        nxt = now.replace(hour=BACKUP_HOUR, minute=0, second=0, microsecond=0)
        if nxt <= now:
            nxt += timedelta(days=1)
        time.sleep((nxt - now).total_seconds())
        with app.app_context():
            try:
                name = backup.run_backup("nightly")
                print(f"[{datetime.now():%Y-%m-%d %H:%M}] Nightly backup created: {name}", flush=True)
            except Exception as e:      # never let a failed backup stop the server
                print(f"[{datetime.now():%Y-%m-%d %H:%M}] Nightly backup FAILED: {e}", flush=True)


if __name__ == "__main__":
    if port_in_use(PORT):
        # two servers on one port answer requests at random, so refuse instead of starting a second one
        print(f"Port {PORT} is already in use: Msururu ERP (serve.py or 'python run.py') or another program is running.", flush=True)
        print("Close the other one first (CTRL+C in its window), then start this again.", flush=True)
        raise SystemExit(1)
    app = create_app()
    threading.Thread(target=nightly_backups, args=(app,), daemon=True, name="nightly-backup").start()
    print("Msururu ERP is running. Open one of these addresses:", flush=True)
    print(f"  This computer : http://127.0.0.1:{PORT}", flush=True)
    for ip in lan_ips():
        print(f"  Network       : http://{ip}:{PORT}", flush=True)
    print(f"Nightly backup at {BACKUP_HOUR:02d}:00 into the 'backups' folder.", flush=True)
    serve(app, host=HOST, port=PORT, threads=8)
