#!/usr/bin/env python3
"""
License key generator — CLI tool for admin use.

Usage:
  python3 -m license_server.keygen generate --tier pro --email user@example.com
  python3 -m license_server.keygen generate --tier trial
  python3 -m license_server.keygen revoke GAT-XXXX-XXXX-XXXX-XXXX
  python3 -m license_server.keygen list
  python3 -m license_server.keygen list --all  # include revoked
"""
from __future__ import annotations

import argparse
import secrets
import string
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from license_server.config import KEY_PREFIX, KEY_GROUP_LENGTH, KEY_GROUPS, TIERS
from license_server.license_store import (
    create_license,
    get_license,
    init_db,
    list_licenses,
    revoke_license,
)

ALPHABET = string.ascii_uppercase + string.digits  # no O/0/I/1 to avoid confusion
ALPHABET = ALPHABET.translate(str.maketrans("", "", "O0I1"))


def generate_key() -> str:
    groups = []
    for _ in range(KEY_GROUPS):
        group = "".join(secrets.choice(ALPHABET) for _ in range(KEY_GROUP_LENGTH))
        groups.append(group)
    return f"{KEY_PREFIX}-{'-'.join(groups)}"


def cmd_generate(args: argparse.Namespace) -> None:
    if args.tier not in TIERS:
        print(f"Invalid tier: {args.tier}. Choices: {', '.join(TIERS)}")
        sys.exit(1)

    key = generate_key()
    lic = create_license(key, args.tier, customer_email=args.email, notes=args.notes or "")
    if not lic:
        print("ERROR: Failed to create license.")
        sys.exit(1)

    print(f"License key generated:\n")
    print(f"  Key:   {key}")
    print(f"  Tier:  {lic['tier']}")
    print(f"  Email: {lic.get('customer_email', '(none)')}")
    print(f"  Expires: {lic.get('expires_at', 'never')}")
    print(f"  Notes:  {lic.get('notes', '')}")


def cmd_revoke(args: argparse.Namespace) -> None:
    ok = revoke_license(args.key, reason=args.reason or "")
    if ok:
        print(f"Revoked: {args.key}")
    else:
        print(f"License not found: {args.key}")
        sys.exit(1)


def cmd_list(args: argparse.Namespace) -> None:
    licenses = list_licenses(include_revoked=args.all)
    if not licenses:
        print("No licenses found.")
        return

    print(f"{'Key':<24} {'Tier':<12} {'Email':<28} {'Expires':<22} {'Status'}")
    print("-" * 110)
    for lic in licenses:
        status = "REVOKED" if lic["revoked"] else "ACTIVE"
        exp = lic.get("expires_at", "")[:10] if lic.get("expires_at") else "never"
        email = lic.get("customer_email", "") or "(none)"
        print(f"{lic['license_key']:<24} {lic['tier']:<12} {email:<28} {exp:<22} {status}")


def main() -> None:
    init_db()

    parser = argparse.ArgumentParser(description="Gold AutoTrade License Key Manager")
    sub = parser.add_subparsers(dest="command")

    gen = sub.add_parser("generate", help="Generate a new license key")
    gen.add_argument("--tier", required=True, choices=list(TIERS), help="License tier")
    gen.add_argument("--email", default="", help="Customer email")
    gen.add_argument("--notes", default="", help="Admin notes")

    rev = sub.add_parser("revoke", help="Revoke a license key")
    rev.add_argument("key", help="License key to revoke")
    rev.add_argument("--reason", default="", help="Revocation reason")

    lst = sub.add_parser("list", help="List all licenses")
    lst.add_argument("--all", action="store_true", help="Include revoked licenses")

    args = parser.parse_args()
    if args.command == "generate":
        cmd_generate(args)
    elif args.command == "revoke":
        cmd_revoke(args)
    elif args.command == "list":
        cmd_list(args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
