# Register this local server with the CNP cloud hub (after license key is in deploy\license-node.json).
param(
    [string]$InstallRoot = "",
    [string]$PublicUrl = ""
)

$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
if (-not $InstallRoot) {
    $InstallRoot = (Resolve-Path (Join-Path $scriptDir "..\..")).Path
}
$configPath = Join-Path $InstallRoot "deploy\license-node.json"
if (-not (Test-Path $configPath)) {
    Write-Host "Missing deploy\license-node.json — run Install-CNPERP-Local.ps1 first." -ForegroundColor Red
    exit 1
}

$cfg = Get-Content $configPath -Raw | ConvertFrom-Json
if (-not $cfg.license_key) {
    Write-Host "Add your CNP license key to deploy\license-node.json (license_key field), then run again." -ForegroundColor Yellow
    exit 1
}

if ($PublicUrl) { $cfg.public_base_url = $PublicUrl }
$python = Join-Path $InstallRoot ".venv\Scripts\python.exe"
if (-not (Test-Path $python)) { $python = "python" }

& $python (Join-Path $InstallRoot "scripts\heartbeat_license.py") --config $configPath
if ($LASTEXITCODE -eq 0) {
    Write-Host "Cloud link registered. Heartbeat task: deploy\setup_license_heartbeat_task.ps1" -ForegroundColor Green
}
