#!/usr/bin/env bash
# Deep link testing script for ABCC Roku app
# Usage:
#   ./deeplink.sh launch <contentId>   — cold start (closes app first, then launches with content)
#   ./deeplink.sh input  <contentId>   — mid-session (app must already be running)
#   ./deeplink.sh list                 — list content IDs from the live feed
#   ./deeplink.sh live                 — launch to live stream (no contentId needed)

ROKU_IP="192.168.40.88"
CHANNEL="dev"
MEDIA_TYPE="movie"
FEED_URL="https://media.abcc.org/roku/feeds/primary-feed.json"

usage() {
    echo "Usage: $0 {launch|input|list|live} [contentId]"
    exit 1
}

cmd="${1}"
contentId="${2}"

case "$cmd" in

  launch)
    [[ -z "$contentId" ]] && { echo "Error: contentId required"; usage; }
    echo "Closing app..."
    curl -s -d '' "http://${ROKU_IP}:8060/keypress/Home" > /dev/null
    sleep 1
    echo "Launching with contentId=${contentId}..."
    curl -s -d '' "http://${ROKU_IP}:8060/launch/${CHANNEL}?contentId=${contentId}&mediaType=${MEDIA_TYPE}"
    echo ""
    echo "Done. Watch debug console: telnet ${ROKU_IP} 8085"
    ;;

  input)
    [[ -z "$contentId" ]] && { echo "Error: contentId required"; usage; }
    echo "Sending mid-session deep link: contentId=${contentId}..."
    curl -s -d '' "http://${ROKU_IP}:8060/input/${CHANNEL}?contentId=${contentId}&mediaType=${MEDIA_TYPE}"
    echo ""
    echo "Done."
    ;;

  live)
    echo "Launching live stream..."
    curl -s -d '' "http://${ROKU_IP}:8060/launch/${CHANNEL}"
    echo ""
    ;;

  list)
    echo "Fetching content IDs from feed..."
    echo ""
    curl -s "$FEED_URL" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for category, items in data.items():
    if isinstance(items, list):
        print(f'--- {category} ---')
        for item in items:
            cid  = item.get('id', '')
            title = item.get('originalTitle') or item.get('title', '')
            print(f'  {cid}  {title[:80]}')
        print()
"
    ;;

  *)
    usage
    ;;
esac
