#!/bin/bash
# screenpunk_skill.sh — screenpunk Claude Code skill runner
# Runs under Claude Code skill only. Outputs JSON to stdout.
# Usage: ./screenpunk_skill.sh

CONFIG="$HOME/.screenpunk"
HISTORY="$HOME/.screenpunk.skill.run"
SCREENSHOT_DIR="$HOME/screenpunk/screenshots"

# Lambda endpoint for remote locations (set once Lambda is deployed)
LAMBDA_URL="https://REPLACE_WITH_LAMBDA_URL"

# ---- Check config ----
if [ ! -f "$CONFIG" ]; then
    echo '{"error":"screenpunk not configured — visit screenpunk.matraex.com to connect"}'
    exit 0
fi

# Read config fields using grep/sed (no jq dependency)
CODE=$(grep -o '"code"\s*:\s*"[^"]*"' "$CONFIG" | sed 's/.*"\([^"]*\)"$/\1/')

# ---- List local screenshots ----
local_files="[]"
if [ -d "$SCREENSHOT_DIR" ]; then
    # Build JSON array of paths, newest first
    local_list=$(ls -t "$SCREENSHOT_DIR" 2>/dev/null | head -20 | while read f; do
        echo "\"$SCREENSHOT_DIR/$f\""
    done | paste -sd, -)
    if [ -n "$local_list" ]; then
        local_files="[$local_list]"
    fi
fi
local_count=$(ls "$SCREENSHOT_DIR" 2>/dev/null | wc -l | tr -d ' ')

# ---- Fetch remote screenshots ----
remote_files="[]"
remote_count=0
if [ -n "$CODE" ] && [ "$LAMBDA_URL" != "https://REPLACE_WITH_LAMBDA_URL" ]; then
    response=$(curl -s -X POST "$LAMBDA_URL" \
        -H "Content-Type: application/json" \
        -d "{\"remotelocationcode\":\"$CODE\",\"limit\":20}" 2>/dev/null)
    if [ -n "$response" ]; then
        # Extract available array from response
        avail=$(echo "$response" | grep -o '"available"\s*:\s*\[[^]]*\]' | sed 's/"available"\s*:\s*//')
        if [ -n "$avail" ]; then
            remote_files="$avail"
            remote_count=$(echo "$avail" | grep -o '"http' | wc -l | tr -d ' ')
        fi
    fi
fi

# ---- Append to history ----
ts=$(date -u +"%Y-%m-%dT%H:%M:%S")
echo "{\"ts\":\"$ts\",\"local_count\":$local_count,\"remote_count\":$remote_count,\"status\":\"ok\"}" >> "$HISTORY"

# ---- Output JSON ----
echo "{\"local\":$local_files,\"remote\":$remote_files}"
