#!/bin/bash
set -e

MANAGER="http://127.0.0.1:19088"
TOKEN="dev-admin-token"
VERSION="0.9.12"
DIGEST="217476014d51e7f54971e9a938625044ddef5e86282c9ed055cc72659c9269ed"
ARTIFACT_ID="artifact-56c16c03-1"  # reuse existing, will update DB
TEST_INSTANCE="friend-4f864178"
MAIN_INSTANCE="friend-043bd076"
CONTAINER_TEST="friend-deploy-f67b3ed2-e3c"
CONTAINER_MAIN="friend-deploy-8ee3dbd3-24b"

# Sign the binary
echo "=== Signing ==="
echo "$DIGEST" | xxd -r -p > /tmp/digest.bin
SIGNATURE=$(openssl pkeyutl -sign -inkey ~/.friend/keys/release-2026-private.pem -rawin -in /tmp/digest.bin | base64 | tr -d '\n')
echo "Signature: ${SIGNATURE:0:40}..."

# Upload to storage pool
echo "=== Uploading to storage pool ==="
UPLOAD_RESULT=$(curl -sS -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/octet-stream" \
  --data-binary @/tmp/friend-agent-linux-amd64 \
  "$MANAGER/api/v1/storage-pools/spool-3b376d8f-1/objects?kind=file&name=friend-agent-${VERSION}-linux-amd64")
echo "Upload: $UPLOAD_RESULT"
SOBJ_ID=$(echo "$UPLOAD_RESULT" | python3 -c "import json,sys;print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
echo "Storage object ID: $SOBJ_ID"

# Update artifact in DB (no DELETE/PUT API available)
echo "=== Updating artifact in DB ==="
python3 << PYEOF
import sqlite3
conn = sqlite3.connect("/opt/friend-cluster/data/friend-cluster-v1.db")
cur = conn.cursor()
cur.execute("UPDATE artifacts SET digest=?, signature=?, storage_object_id=?, size_bytes=? WHERE id=?",
            ("sha256:$DIGEST", "$SIGNATURE", "$SOBJ_ID", $(stat -c%s /tmp/friend-agent-linux-amd64), "$ARTIFACT_ID"))
print(f"Updated artifact {cur.rowcount} row(s)")
conn.commit()
conn.close()
PYEOF

SOURCE_URL="http://10.200.0.10:19088/artifact-content/$ARTIFACT_ID/$DIGEST"

# Write trust key to test container (in case not present)
echo "=== Writing trust key to test container ==="
docker exec $CONTAINER_TEST sh -c 'mkdir -p /var/lib/friend-cluster && echo "release-2026=qEvynp6sTeb1a5iMkorOdhjVN0tznJIPd/MGTk/+PsE=" > /var/lib/friend-cluster/artifact-trust-key' 2>/dev/null || true

# Also write to main container
docker exec $CONTAINER_MAIN sh -c 'mkdir -p /var/lib/friend-cluster && echo "release-2026=qEvynp6sTeb1a5iMkorOdhjVN0tznJIPd/MGTk/+PsE=" > /var/lib/friend-cluster/artifact-trust-key' 2>/dev/null || true

# Trigger agent.upgrade on test instance
echo "=== Triggering agent.upgrade on test instance ==="
UPGRADE_RESULT=$(curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{
    \"action\": \"agent.upgrade\",
    \"payload\": {
      \"program\": \"friend-agent\",
      \"version\": \"$VERSION\",
      \"source_url\": \"$SOURCE_URL\",
      \"digest\": \"sha256:$DIGEST\",
      \"signature\": \"$SIGNATURE\",
      \"key_id\": \"release-2026\"
    }
  }" \
  "$MANAGER/api/v1/instances/$TEST_INSTANCE/commands")
echo "Upgrade: $UPGRADE_RESULT"

# Also upgrade main instance
echo "=== Triggering agent.upgrade on main instance ==="
UPGRADE_MAIN=$(curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{
    \"action\": \"agent.upgrade\",
    \"payload\": {
      \"program\": \"friend-agent\",
      \"version\": \"$VERSION\",
      \"source_url\": \"$SOURCE_URL\",
      \"digest\": \"sha256:$DIGEST\",
      \"signature\": \"$SIGNATURE\",
      \"key_id\": \"release-2026\"
    }
  }" \
  "$MANAGER/api/v1/instances/$MAIN_INSTANCE/commands")
echo "Main upgrade: $UPGRADE_MAIN"

echo "=== Waiting for upgrades to complete ==="
sleep 30

# Check status
echo "=== Test instance status ==="
curl -sS -H "Authorization: Bearer $TOKEN" "$MANAGER/api/v1/instances/$TEST_INSTANCE" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
inst=d.get('instance',d)
print('config_state:', inst.get('config_state',''))
print('desired_config_generation:', inst.get('desired_config_generation',''))
print('applied_config_generation:', inst.get('applied_config_generation',''))
print('extension_state:', inst.get('extension_state',''))
print('health_state:', inst.get('health_state',''))
print('last_error:', inst.get('last_error','')[:300])
"

echo ""
echo "=== Main instance status ==="
curl -sS -H "Authorization: Bearer $TOKEN" "$MANAGER/api/v1/instances/$MAIN_INSTANCE" 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin)
inst=d.get('instance',d)
print('config_state:', inst.get('config_state',''))
print('health_state:', inst.get('health_state',''))
print('last_error:', inst.get('last_error','')[:300])
"

# Check test instance plugin health
echo ""
echo "=== Test instance plugin health ==="
docker exec $CONTAINER_TEST sh -c 'curl -sS http://127.0.0.1:8000/api/plugins/llm-proxy/health 2>/dev/null' || echo "unauthorized"
echo ""

# Check test instance LLM overview
echo "=== Test instance LLM overview ==="
docker exec $CONTAINER_TEST sh -c 'curl -sS http://127.0.0.1:8000/api/llm/overview 2>/dev/null' || echo "unauthorized"
echo ""
