#!/bin/bash
set -e

MANAGER="http://127.0.0.1:19088"
TOKEN="dev-admin-token"
VERSION="0.9.12"
DIGEST="217476014d51e7f54971e9a938625044ddef5e86282c9ed055cc72659c9269ed"
SIGNATURE="k3par3QgLeRjTbGtM1Bodzc8dzSlKUc685WilD8UMPvWHWhSq85HKXR08RGhQxZg/r8HwBa3RpIkD8v/hbSTDw=="
ARTIFACT_ID="artifact-56c16c03-1"
SOBJ_ID="sobj-46e6b159-b"
TEST_INSTANCE="friend-4f864178"
MAIN_INSTANCE="friend-043bd076"
CONTAINER_TEST="friend-deploy-f67b3ed2-e3c"
CONTAINER_MAIN="friend-deploy-8ee3dbd3-24b"

# Update artifact in DB with correct signature
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", 10524115, "$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 both containers
echo "=== Writing trust key ==="
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
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 ==="
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 ""

# Trigger agent.upgrade on main instance
echo "=== Triggering agent.upgrade on main instance ==="
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 ""

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

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])
"

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 ""

echo "=== Test instance extensions ==="
curl -sS -H "Authorization: Bearer $TOKEN" "$MANAGER/api/v1/instances/$TEST_INSTANCE/extensions" 2>/dev/null
echo ""
