"""CLI commands for license activation and info display."""
from __future__ import annotations


def cmd_activate(args: list):
    """Activate a license key: pulse activate PULSE-SOLO-cus_xxx-sig."""
    if not args:
        print("Usage: pulse activate <LICENSE_KEY>")
        print("  Get your key at https://pulseos.dev/pricing")
        return

    key = args[0]
    from pulse.core.license import LicenseManager
    lm = LicenseManager()

    parsed = lm._parse_key(key)
    if not parsed:
        print("[PULSE] Invalid license key format.")
        print("  Keys look like: PULSE-SOLO-cus_abc123-xxxxxx")
        return

    print("[PULSE] Validating key...")
    result = lm.validate_key(key)
    if not result:
        print("[PULSE] Validation failed. Check your key and ensure STRIPE_SECRET_KEY is set.")
        return

    lm.save_license(key, result)
    status = result.get("status", "unknown")
    plan = result.get("plan", "unknown")
    trial_end = result.get("trial_end")

    print("[PULSE] License activated!")
    print(f"  Plan:   {plan.upper()}")
    print(f"  Status: {status}")
    if trial_end:
        import datetime
        dt = datetime.datetime.fromtimestamp(trial_end, tz=datetime.timezone.utc)
        print(f"  Trial ends: {dt.strftime('%Y-%m-%d')}")
    limits = lm.get_limits()
    max_w = limits.get("max_workers")
    print(f"  Workers: {'unlimited' if max_w is None else max_w}")
    print("\n  Run 'pulse status' to verify.")


def cmd_license_info(args: list):
    """Show current license and plan info."""
    from pulse.core.license import LicenseManager
    lm = LicenseManager()
    plan = lm.get_plan()
    limits = lm.get_limits()
    lic = lm.load_license()

    print("=" * 50)
    print("  PULSE License Info")
    print("=" * 50)

    from pulse.core.paths import _is_dev_mode
    if _is_dev_mode():
        print("  Mode:    Developer (all features enabled)")
        print("  Plan:    pro (dev override)")
        return

    if not lic:
        print("  Status:  No license")
        print(f"  Plan:    {plan}")
        print("\n  Activate: pulse activate <KEY>")
        print("  Get key:  https://pulseos.dev/pricing")
        return

    status = lic.get("status", "unknown")
    print(f"  Plan:    {lic.get('plan', plan).upper()}")
    print(f"  Status:  {status}")
    trial_end = lic.get("trial_end")
    if trial_end:
        import datetime
        dt = datetime.datetime.fromtimestamp(trial_end, tz=datetime.timezone.utc)
        print(f"  Trial ends: {dt.strftime('%Y-%m-%d')}")
    max_w = limits.get("max_workers")
    print(f"  Workers: {'unlimited' if max_w is None else max_w}")
    daemons = limits.get("daemons")
    print(f"  Daemons: {'all' if daemons is None else len(daemons)}")
    warning = lic.get("_warning")
    if warning:
        print(f"\n  Warning: {warning}")
    if status == "canceled":
        print("\n  Your subscription has ended. Renew at https://pulseos.dev/pricing")
