#!/bin/bash
# Full Cycle Demo: Registration -> Suggestion -> Review -> Execution -> Visualization

API_URL="http://localhost:3003"
API_KEY="muser_68600856036340bcafc01930eb4bd839_1774418104_97221b69"
UUID="384b0ff44aaaa1f1"

print_header() {
	echo ""
	echo "============================================================"
	echo "  🎬 $1"
	echo "============================================================"
}

print_step() {
	echo "👉 $1"
}

print_json() {
	echo "$1" | python3 -m json.tool 2>/dev/null || echo "$1"
}

# --- Setup: Ensure clean state for demo ---
print_header "PHASE 0: PREPARATION"
print_step "Resetting Person_25 to simulate a duplicate entry..."

# Ensure Person_25 exists as a separate entity for the demo
psql -h localhost -U accusys -d momentry <<SQL
INSERT INTO dev.person_identities (person_id, video_uuid, appearance_count, name, speaker_id)
VALUES ('Person_25', '$UUID', 217, NULL, 'SPEAKER_1')
ON CONFLICT (person_id) DO UPDATE SET name = EXCLUDED.name, speaker_id = EXCLUDED.speaker_id;

INSERT INTO dev.person_appearances (person_id, video_uuid, start_time, end_time, duration, confidence)
VALUES ('Person_25', '$UUID', 100.0, 150.0, 50.0, 0.9)
ON CONFLICT DO NOTHING;
SQL

# --- PHASE 1: Registration ---
print_header "PHASE 1: REGISTRATION"
print_step "Registering Person_17 as Audrey Hepburn..."

RES_REGISTER=$(curl -s -X POST "$API_URL/api/v1/identities/from-person" \
	-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
	-d "{
    \"video_uuid\": \"$UUID\",
    \"person_id\": \"Person_17\",
    \"identity_name\": \"Audrey Hepburn\",
    \"metadata\": { \"role\": \"Reggie Lampert\" }
  }")

echo "   ✅ API Response:"
print_json "$RES_REGISTER"

# --- PHASE 2: Visualization (Before) ---
print_header "PHASE 2: VISUALIZATION (BEFORE)"
print_step "Current State of 'Audrey Hepburn' Candidates"

# Query and format the list of persons
curl -s "$API_URL/api/v1/person/list?video_uuid=$UUID&limit=20" \
	-H "X-API-Key: $API_KEY" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"   Found {data['total']} persons.\")
print(f\"   {'ID':<15} | {'Name':<20} | {'Speaker':<15} | {'Frames'}\")
print(f\"   {'-'*15}-|-{'-'*20}-|-{'-'*15}-|-{'-'*10}\")
for p in data['persons']:
    pid = p['person_id']
    name = p.get('name') or '<Unknown>'
    speaker = p.get('speaker_id') or 'None'
    frames = p['appearance_count']
    if pid in ['Person_17', 'Person_25']:
        print(f\"   {pid:<15} | {name:<20} | {speaker:<15} | {frames}\")
"

# --- PHASE 3: Suggestion ---
print_header "PHASE 3: SUGGESTION (AI REVIEW)"
print_step "Asking AI to analyze duplicates..."

RES_SUGGEST=$(curl -s -X POST "$API_URL/api/v1/person/suggest" \
	-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
	-d "{\"video_uuid\": \"$UUID\"}")

echo "   🤖 AI Analysis:"
python3 -c "
import json
data = json.loads('''$RES_SUGGEST''')
merges = data.get('merge_suggestions', [])
for m in merges:
    print(f\"   - Suggestion: Merge {m['merge_with']} -> {m['person_id']}\")
    print(f\"     Reason: {m['reasons'][0]}\")
    print(f\"     Action: {m['action']}\")
if not merges:
    print(\"   No merge suggestions found (Data might be clean or algorithm needs data).\")
"

# --- PHASE 4: Execution ---
print_header "PHASE 4: EXECUTION"
print_step "Executing Merge: Person_25 -> Person_17..."

RES_MERGE=$(curl -s -X POST "$API_URL/api/v1/person/merge" \
	-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
	-d "{
    \"video_uuid\": \"$UUID\",
    \"target_person_id\": \"Person_17\",
    \"source_person_ids\": [\"Person_25\"]
  }")

echo "   ✅ Merge Result:"
print_json "$RES_MERGE"

# --- PHASE 5: Visualization (After) ---
print_header "PHASE 5: VISUALIZATION (AFTER)"
print_step "Final State Verification"

curl -s "$API_URL/api/v1/person/list?video_uuid=$UUID&limit=20" \
	-H "X-API-Key: $API_KEY" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"   {'ID':<15} | {'Name':<20} | {'Speaker':<15} | {'Frames'}\")
print(f\"   {'-'*15}-|-{'-'*20}-|-{'-'*15}-|-{'-'*10}\")
for p in data['persons']:
    pid = p['person_id']
    name = p.get('name') or '<Unknown>'
    speaker = p.get('speaker_id') or 'None'
    frames = p['appearance_count']
    if pid == 'Person_17':
        print(f\"   {pid:<15} | {name:<20} | {speaker:<15} | {frames} (✅ MERGED)\")
    elif pid == 'Person_25':
        print(f\"   {pid:<15} | {name:<20} | {speaker:<15} | {frames} (❌ DELETED)\")
"

print_header "✅ DEMO COMPLETE"
