#!/usr/bin/env python3
"""
License activation CLI — activate a license key on this machine.

Usage:
  python3 -m src.license.activate --key GAT-XXXX-XXXX-XXXX-XXXX --server https://license.huipin199.com
  python3 -m src.license.activate --key GAT-XXXX-XXXX-XXXX-XXXX  # uses default server
  python3 -m src.license.activate --status                        # show current license status
"""
from __future__ import annotations

import argparse
import json
import sys
import urllib.request
import urllib.error
from pathlib import Path

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

from src.license.validator import _get_hardware_id, save_license, get_license_status

DEFAULT_SERVER = "https://license.huipin199.com"


def activate(license_key: str, server_url: str = DEFAULT_SERVER) -> int:
    hardware_id = _get_hardware_id()
    machine_name = __import__("platform").node() or "unknown"

    body = json.dumps({
        "license_key": license_key,
        "hardware_id": hardware_id,
        "machine_name": machine_name,
    }).encode()

    print(f"Activating license...")
    print(f"  Key:     {license_key}")
    print(f"  Machine: {machine_name}")
    print(f"  HW ID:   {hardware_id}")
    print()

    try:
        req = urllib.request.Request(
            f"{server_url}/activate",
            data=body,
            headers={"Content-Type": "application/json"},
        )
        with urllib.request.urlopen(req, timeout=15) as resp:
            result = json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        try:
            result = json.loads(e.read().decode())
        except Exception:
            result = {"ok": False, "error": f"HTTP {e.code}"}
    except Exception as e:
        print(f"ERROR: Cannot reach license server at {server_url}")
        print(f"  {e}")
        return 1

    if result.get("ok"):
        signed = result.get("signed_license")
        if signed and save_license(signed):
            print("SUCCESS: License activated!")
            status = get_license_status()
            print(f"  Tier:     {status.get('tier', 'unknown')}")
            print(f"  Expires:  {status.get('expires', 'never')}")
            print(f"  Features: {', '.join(status.get('features', []))}")
            return 0
        else:
            print("ERROR: Activation succeeded but failed to save license file.")
            return 1
    else:
        print(f"ERROR: {result.get('message', result.get('error', 'Activation failed'))}")
        return 1


def show_status() -> None:
    status = get_license_status()
    print(f"License Status: {status['status']}")
    if status["status"] == "ACTIVE":
        print(f"  Tier:     {status['tier']}")
        print(f"  Email:    {status['email']}")
        print(f"  Expires:  {status['expires']}")
        print(f"  Features: {', '.join(status['features'])}")
        print(f"  HW ID:    {status.get('hardware_id', '')}")
    else:
        print(f"  {status['message']}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Gold AutoTrade License Activation")
    parser.add_argument("--key", help="License key (format: GAT-XXXX-XXXX-XXXX-XXXX)")
    parser.add_argument("--server", default=DEFAULT_SERVER, help="License server URL")
    parser.add_argument("--status", action="store_true", help="Show current license status")
    args = parser.parse_args()

    if args.status:
        show_status()
    elif args.key:
        sys.exit(activate(args.key, args.server))
    else:
        parser.print_help()
        sys.exit(1)


if __name__ == "__main__":
    main()
