#!/usr/bin/env python3
"""
Fetch card #903 from Trello and execute the sharing fix.
"""
import json
import os
import subprocess
import sys

def get_card_via_api():
    """Try to fetch card via Trello API using credentials."""
    card_id = "6a1d64126a923744238639f9"
    
    # Try environment variables or common credential locations
    api_key = os.environ.get('TRELLO_API_KEY')
    api_token = os.environ.get('TRELLO_API_TOKEN')
    
    if not api_key or not api_token:
        # Check if we can find credentials
        import urllib.request
        import urllib.error
        
        # For now, return None - we'll handle via stdin
        return None
    
    url = f"https://api.trello.com/1/cards/{card_id}?key={api_key}&token={api_token}&fields=desc,name"
    
    try:
        import urllib.request
        with urllib.request.urlopen(url, timeout=10) as response:
            return json.loads(response.read().decode())
    except Exception as e:
        print(f"ERROR fetching card: {e}", file=sys.stderr)
        return None

def main():
    # Try to get the card
    card = get_card_via_api()
    
    if not card:
        # Try stdin
        try:
            card = json.load(sys.stdin)
        except:
            card = None
    
    if not card or 'desc' not in card:
        print(json.dumps({
            "cardShort": 903,
            "results": [],
            "allWriter": False,
            "problems": ["FAILED_TO_FETCH_CARD"]
        }))
        sys.exit(1)
    
    # Now run the processor with the card description
    description = card.get('desc', '')
    
    result = subprocess.run(
        ["python3", "/opt/automator/cinik-writer-transtor/files/EXECUTE_CARD_903_FIX.py", description],
        capture_output=True,
        text=True
    )
    
    print(result.stdout)
    if result.stderr:
        print(f"STDERR: {result.stderr}", file=sys.stderr)
    
    sys.exit(result.returncode)

if __name__ == "__main__":
    main()
