# Deploy recall endpoint fix to RMM server
# Uses plink/pscp for Windows compatibility

$ErrorActionPreference = "Stop"

$sourceFile = "D:\ClaudeTools\api\routers\conversation_contexts.py"
$rmmHost = "guru@172.16.3.30"
$tempFile = "/tmp/conversation_contexts.py"
$targetFile = "/opt/claudetools/api/routers/conversation_contexts.py"

Write-Host "[1/3] Copying file to RMM server..." -ForegroundColor Cyan
& pscp -batch $sourceFile "${rmmHost}:${tempFile}"

if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Failed to copy file" -ForegroundColor Red
    Write-Host "Try running: pscp $sourceFile ${rmmHost}:${tempFile}" -ForegroundColor Yellow
    exit 1
}

Write-Host "[2/3] Moving file to production location..." -ForegroundColor Cyan
& plink -batch $rmmHost "sudo mv $tempFile $targetFile && sudo chown claudetools:claudetools $targetFile"

if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Failed to move file" -ForegroundColor Red
    exit 1
}

Write-Host "[3/3] Restarting API service..." -ForegroundColor Cyan
& plink -batch $rmmHost "sudo systemctl restart claudetools-api && sleep 2 && sudo systemctl status claudetools-api --no-pager | head -15"

Write-Host ""
Write-Host "[SUCCESS] Deployment complete!" -ForegroundColor Green
Write-Host ""
Write-Host "Testing API..." -ForegroundColor Cyan

# Test the API
python - @"
import requests
import json

jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJpbXBvcnQtc2NyaXB0Iiwic2NvcGVzIjpbImFkbWluIiwiaW1wb3J0Il0sImV4cCI6MTc3MTI3NTEyOX0.-DJF50tq0MaNwVQBdO7cGYNuO5pQuXte-tTj5DpHi2U"

response = requests.get(
    "http://172.16.3.30:8001/api/conversation-contexts/recall",
    headers={"Authorization": f"Bearer {jwt_token}"},
    params={"search_term": "dataforth", "limit": 2}
)

print(f"API Status: {response.status_code}")
data = response.json()

if "contexts" in data:
    print("[SUCCESS] Recall endpoint updated!")
    print(f"Total: {data['total']}, Returned: {len(data['contexts'])}")
    for ctx in data['contexts']:
        print(f"  - {ctx['title'][:60]}")
else:
    print("[WARNING] Still old format")
    print(json.dumps(data, indent=2)[:300])
"@
