#!/bin/bash
# Set Figma URL for a product
# Usage: ./figma-set-url.sh <product-name> <figma-url>

set -e

PRODUCT="${1:?Product name required}"
FIGMA_URL="${2:?Figma URL required}"
PROJECT_DIR="/home/aria/projects/$PRODUCT"
WORKFLOW="$PROJECT_DIR/agency/artifacts/design/workflow.json"
SCREENS="$PROJECT_DIR/agency/artifacts/design/screens.md"

# Validate URL format
if [[ ! "$FIGMA_URL" =~ ^https://www\.figma\.com/(design|file)/ ]]; then
    echo "Error: Invalid Figma URL format" >&2
    echo "Expected: https://www.figma.com/design/... or https://www.figma.com/file/..." >&2
    exit 1
fi

# Extract file key from URL
FILE_KEY=$(echo "$FIGMA_URL" | sed -E 's|.*/design/([^/]+)/.*|\1|' | sed -E 's|.*/file/([^/]+)/.*|\1|')

# Update workflow.json if it exists
if [ -f "$WORKFLOW" ]; then
    TIMESTAMP=$(date -Iseconds)
    jq --arg url "$FIGMA_URL" --arg key "$FILE_KEY" --arg at "$TIMESTAMP" \
        '.figma.status = "ready" | .figma.file_url = $url | .figma.file_id = $key | .figma.created_at = $at | .state = "figma_ready"' \
        "$WORKFLOW" > "$WORKFLOW.tmp" && mv "$WORKFLOW.tmp" "$WORKFLOW"
    echo "✅ Updated workflow.json"
fi

# Update screens.md if it exists
if [ -f "$SCREENS" ]; then
    sed -i "s|🎨 \*\*Figma Link:\*\* \[Not yet created\]|🎨 **Figma Link:** [$FIGMA_URL]($FIGMA_URL)|" "$SCREENS"
    echo "✅ Updated screens.md"
fi

echo ""
echo "=============================================="
echo "🎨 Figma URL set for: $PRODUCT"
echo "=============================================="
echo "URL: $FIGMA_URL"
echo "File Key: $FILE_KEY"
echo ""
echo "Next steps:"
echo "1. Import screen PNGs into Figma"
echo "2. Organize frames by flow"
echo "3. Run: ./design-workflow.sh $PRODUCT complete <approver>"
echo "=============================================="
