"""Vertex ERP — run with:  python app.py [--reset] [--empty] [--port 8000]"""
import argparse
import os

from vertex import create_app
from vertex.db import create_schema

parser = argparse.ArgumentParser(description="Vertex ERP")
parser.add_argument("--reset", action="store_true", help="delete the database and start over")
parser.add_argument("--empty", action="store_true", help="when creating the database, skip demo transactions")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--dev", action="store_true", help="use Flask's development server instead of Waitress")
parser.add_argument("--threads", type=int, default=8)
parser.add_argument("--db", help="database file (default instance/vertex.db)")
parser.add_argument("--business", default="custom", choices=["trading", "contracting", "services", "custom"],
                    help="when creating the database: the type of business (its modules and demo story)")
args = parser.parse_args()

app = create_app(args.db) if args.db else create_app()
db_path = app.config["DATABASE"]
if args.reset and os.path.exists(db_path):
    os.remove(db_path)
if not os.path.exists(db_path):
    from vertex.seed import seed
    create_schema(db_path)
    with app.app_context():
        seed(demo=not args.empty, business=args.business)
    print("Database created" + ("" if args.empty else " with demo data") + ".")
    print("Log in with admin / admin123")

if __name__ == "__main__":
    try:
        if args.dev:
            raise ImportError
        from waitress import serve  # production server (Windows, macOS, Linux)
        print(f"Vertex ERP on http://{args.host}:{args.port}")
        serve(app, host=args.host, port=args.port, threads=args.threads)
    except ImportError:
        app.run(host=args.host, port=args.port, debug=False)
