#!/bin/bash
set -e

CARD_ID="6a1d64126a923744238639f9"
SCRIPT_PATH="/opt/automator/cinik-writer-transtor/files/RUN_CARD_921_SHARE_FIX.py"

# Since we have the Trello MCP loaded, we need to invoke it
# The MCP should return the card data as JSON
# For now, let's try with a manual fetch using curl

# Option 1: Try to use Node.js with MCP if available
# Option 2: Use Trello API directly if we have credentials
# Option 3: Read from a previously saved file

# Let's try creating a quick Node.js script that uses the Trello MCP
cat > /tmp/fetch_card_mcp.js << 'JSEOF'
const {spawn} = require('child_process');
const fs = require('fs');
const path = require('path');

// The MCP is already loaded, so we should be able to access it
// For now, we'll try a workaround: use curl to fetch the card directly

const cardId = "6a1d64126a923744238639f9";

// Try to read Trello API credentials from environment or files
let trelloKey = process.env.TRELLO_KEY;
let trelloToken = process.env.TRELLO_TOKEN;

if (!trelloKey || !trelloToken) {
    console.error("ERROR: TRELLO_KEY and TRELLO_TOKEN not set");
    console.error("Please set these environment variables or use stdin");
    process.exit(1);
}

const url = `https://api.trello.com/1/cards/${cardId}?key=${trelloKey}&token=${trelloToken}&fields=desc,name`;

const https = require('https');
https.get(url, (res) => {
    let data = '';
    res.on('data', chunk => data += chunk);
    res.on('end', () => {
        if (res.statusCode !== 200) {
            console.error(`HTTP ${res.statusCode}: ${data}`);
            process.exit(1);
        }
        console.log(data);
    });
}).on('error', (e) => {
    console.error(`Error: ${e}`);
    process.exit(1);
});
JSEOF

# Check if Node.js is available
if command -v node &> /dev/null; then
    echo "Using Node.js to fetch card..." >&2
    CARD_DATA=$(node /tmp/fetch_card_mcp.js 2>/dev/null || echo "{}")
    if [ "$CARD_DATA" != "{}" ]; then
        echo "$CARD_DATA" | python3 "$SCRIPT_PATH"
        exit $?
    fi
fi

# Fallback: Try with curl directly
if command -v curl &> /dev/null && [ -n "$TRELLO_KEY" ] && [ -n "$TRELLO_TOKEN" ]; then
    echo "Using curl to fetch card..." >&2
    CARD_DATA=$(curl -s "https://api.trello.com/1/cards/${CARD_ID}?key=${TRELLO_KEY}&token=${TRELLO_TOKEN}&fields=desc,name" 2>/dev/null || echo "{}")
    if [ "$CARD_DATA" != "{}" ]; then
        echo "$CARD_DATA" | python3 "$SCRIPT_PATH"
        exit $?
    fi
fi

# Final fallback: Wait for data from stdin
echo "No Trello credentials found. Expecting card JSON on stdin..." >&2
python3 "$SCRIPT_PATH"

