"""Run Msururu ERP for development:  python run.py

Listens on the network too and prints the addresses to open. Code changes reload automatically.
The interactive debugger is off, because the page is reachable from other computers.
For everyday use by staff, run serve.py instead (production server + nightly backups).
"""
import os
from app import create_app
from app.utils.net import banner, port_in_use, lan_ips

app = create_app()

if __name__ == "__main__":
    wanted = int(os.environ.get("MIZANI_PORT", "5000"))
    if os.environ.get("WERKZEUG_RUN_MAIN") != "true":          # first start (not the auto-reload child): choose port, print once
        port = wanted
        if port_in_use(port):
            port = next(p for p in range(wanted + 1, wanted + 50) if not port_in_use(p))
            print(f"Port {wanted} is already in use (serve.py is probably running): staff on the network keep using it at")
            for ip in lan_ips():
                print(f"  http://{ip}:{wanted}")
            print(f"This development copy uses port {port} instead.\n")
        os.environ["MIZANI_DEV_PORT"] = str(port)
        print(banner(port), flush=True)
        if port != 5000:
            print(f"  Note: the firewall lets other computers in on port 5000 only, so port {port} works from this PC;"
                  f" staff should use the port 5000 address shown above.")
        print("Press CTRL+C to stop.\n", flush=True)
    port = int(os.environ["MIZANI_DEV_PORT"])
    app.run(host="0.0.0.0", port=port, debug=True, use_debugger=False, use_reloader=True)
