"""Small admin helper. Run on the server (cPanel Terminal, inside the app's virtualenv):

  python manage.py list
  python manage.py buy https://your-payment-or-whatsapp-link
  python manage.py import Licenses.csv      # old Google Sheet "Licenses" tab exported as CSV
"""
import csv
import sys

import licensing


def main():
    a = sys.argv[1:]
    if not a:
        print(__doc__)
        return
    if a[0] == "list":
        d = licensing.run("admin_list", {})
        for l in d["licenses"]:
            print(l["code"], l["seats"], l["used"], l["status"], l["expires"] or "Lifetime", l["customer"])
        print(len(d["licenses"]), "licenses,", len(d["activations"]), "activations")
    elif a[0] == "buy" and len(a) > 1:
        print(licensing.run("admin_set", {"name": "buy_url", "value": a[1]}))
    elif a[0] == "import" and len(a) > 1:
        n = 0
        with open(a[1], newline="", encoding="utf-8-sig") as f:
            for i, row in enumerate(csv.reader(f)):
                if i == 0 or not row or not row[0].strip():
                    continue
                row += [""] * 6
                r = licensing.run("admin_add", {"code": row[0], "seats": row[1] or 1, "customer": row[2],
                                                "expires": row[5]})
                if r.get("ok"):
                    n += 1
                    if str(row[4]).strip().lower() == "revoked":
                        licensing.run("admin_revoke", {"code": row[0]})
        print("imported", n, "licenses")
    else:
        print(__doc__)


main()
