#!/usr/bin/env python3
"""
Fetch Trello card description by ID.
Tries multiple auth approaches.
"""
import os
import sys
import json
import urllib.request
import urllib.error

CARD_ID = "6a1d693f049c86ebcbdacbc8"

# Try to get credentials from environment or config files
def get_trello_credentials():
    """Try to find Trello API credentials"""
    
    # Check environment variables first
    api_key = os.getenv('TRELLO_API_KEY')
    token = os.getenv('TRELLO_TOKEN')
    
    if api_key and token:
        return api_key, token
    
    # Check common config locations
    config_paths = [
        os.path.expanduser("~/.trello"),
        os.path.expanduser("~/.trello.json"),
        os.path.expanduser("~/.config/trello.json"),
        "/etc/trello.json"
    ]
    
    for path in config_paths:
        if os.path.exists(path):
            try:
                with open(path) as f:
                    config = json.load(f)
                    api_key = config.get('api_key') or config.get('key')
                    token = config.get('token')
                    if api_key and token:
                        return api_key, token
            except:
                pass
    
    return None, None

# Try fetch
api_key, token = get_trello_credentials()

if not api_key or not token:
    # Try a different approach - check if jq can help with stored auth
    import subprocess
    result = subprocess.run(['env', '|', 'grep', '-i', 'trello'], 
                          capture_output=True, text=True, shell=True)
    if result.stdout:
        print(result.stdout)
    
    print("ERROR: Trello credentials not found", file=sys.stderr)
    print("Set TRELLO_API_KEY and TRELLO_TOKEN env vars", file=sys.stderr)
    sys.exit(1)

# Fetch the card
url = f"https://api.trello.com/1/cards/{CARD_ID}?key={api_key}&token={token}&fields=desc"

try:
    with urllib.request.urlopen(url) as response:
        card = json.load(response)
        print(json.dumps(card, indent=2))
except urllib.error.URLError as e:
    print(f"ERROR fetching card: {e}", file=sys.stderr)
    print(f"URL: {url[:100]}...", file=sys.stderr)
    sys.exit(1)
