#!/usr/bin/env python3
"""Activate a CNPERP local install — bind license to this machine (called by installers)."""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))


def main() -> int:
    parser = argparse.ArgumentParser(description="Activate CNPERP local server with a CNP license")
    parser.add_argument("--license-key", required=True, help="CNP license key from God Mode")
    parser.add_argument("--cloud-url", default="https://erp.cnpsolutions.co.bw")
    parser.add_argument("--public-url", default="", help="LAN URL e.g. http://192.168.1.10:8010")
    parser.add_argument("--node-name", default="")
    args = parser.parse_args()

    from app.services.local_server_license import activate_local_server

    result = activate_local_server(
        args.license_key,
        cloud_url=args.cloud_url,
        node_name=args.node_name or None,
        public_base_url=args.public_url or None,
    )
    if not result.get("success"):
        print(f"[activate] FAILED: {result.get('message')}", file=sys.stderr)
        return 1
    print(f"[activate] OK — {result.get('message')}")
    print(f"[activate] Key: {result.get('key_prefix')}  Node: {result.get('node_id')}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
