#!/usr/bin/env python3
"""
Issue a new CNP license key (CNP staff).

  python scripts/issue_license.py --plan standard --years 1 --customer "Acme Trading"
  python scripts/issue_license.py --plan professional --years 1 --email billing@acme.co.bw --deployment local

Requires CNP_LICENSE_ADMIN_SECRET only when using the HTTP API; this script writes directly to the DB.
"""
import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from app.core.database import SessionLocal
from app.services.licensing_service import LicensingService


def main():
    p = argparse.ArgumentParser(description="Issue a CNP ERP license key")
    p.add_argument("--plan", default="standard", help="standard | professional | enterprise")
    p.add_argument("--years", type=int, default=1)
    p.add_argument("--deployment", default="both", choices=["cloud", "local", "both"])
    p.add_argument("--customer", dest="customer_name", default=None)
    p.add_argument("--email", dest="customer_email", default=None)
    p.add_argument("--max-users", type=int, default=25)
    p.add_argument("--max-branches", type=int, default=10)
    p.add_argument("--notes", default=None)
    args = p.parse_args()

    db = SessionLocal()
    try:
        svc = LicensingService(db)
        record, full_key = svc.issue_license(
            plan=args.plan,
            years=args.years,
            deployment_mode=args.deployment,
            customer_name=args.customer_name,
            customer_email=args.customer_email,
            max_users=args.max_users,
            max_branches=args.max_branches,
            notes=args.notes,
        )
        db.commit()
        print("\n=== CNP License issued ===")
        print(f"License ID : {record.id}")
        print(f"Plan       : {record.plan}")
        print(f"Valid until: {record.valid_until.date().isoformat()}")
        print(f"Deployment : {record.deployment_mode}")
        print(f"\nLICENSE KEY (send to customer once):\n\n  {full_key}\n")
        print("Store this key securely — it cannot be recovered from the database.\n")
    finally:
        db.close()


if __name__ == "__main__":
    main()
