#!/usr/bin/env python3
"""
Fetch Trello card #903, parse docs, and fix sharing for non-FR docs.
"""
import json
import re
import subprocess
import sys
import os

# Try to fetch card 903 using curl + Trello API
# First, let's try to get credentials from common locations

def get_trello_api_credentials():
    """Try to find Trello API credentials."""
    # Try environment variables first
    key = os.environ.get('TRELLO_API_KEY')
    token = os.environ.get('TRELLO_API_TOKEN')
    
    if key and token:
        return key, token
    
    # Try common credential files
    credential_files = [
        os.path.expanduser('~/.trello-api-key'),
        os.path.expanduser('~/.trello-api-token'),
        '/etc/trello-credentials',
    ]
    
    # Also check if there's a config in home
    config_path = os.path.expanduser('~/.trello-mcp/config.json')
    if os.path.exists(config_path):
        try:
            with open(config_path) as f:
                config = json.load(f)
                # Config might have board ID but not auth - check for key/token
                if 'key' in config and 'token' in config:
                    return config['key'], config['token']
        except:
            pass
    
    return None, None

def fetch_card_via_trello_api(card_id):
    """Fetch card from Trello API."""
    key, token = get_trello_api_credentials()
    
    if not key or not token:
        # Try to use a fallback - return card data from stdin or command line
        return None
    
    import urllib.request
    import urllib.error
    
    url = f"https://api.trello.com/1/cards/{card_id}?key={key}&token={token}&fields=desc,name"
    
    try:
        with urllib.request.urlopen(url) as response:
            return json.loads(response.read().decode())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            return None  # Auth failed
        raise
    except Exception:
        return None

def parse_docs_from_description(description):
    """Extract Google Docs from card description."""
    docs = {}
    if not description:
        return docs
    
    # Match: lang: https://docs.google.com/document/d/DOCID/...
    pattern = r'(\w+)\s*:\s*https://docs\.google\.com/document/d/([a-zA-Z0-9-_]+)'
    
    for match in re.finditer(pattern, description):
        lang = match.group(1).lower()
        doc_id = match.group(2)
        docs[lang] = doc_id
    
    return docs

def share_doc(doc_id, lang):
    """Run _share_fix.py share command on a doc."""
    try:
        result = subprocess.run(
            ["python3", "/opt/automator/cinik-writer-transtor/files/_share_fix.py", 
             "share", doc_id],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        if result.returncode != 0:
            return {
                "lang": lang,
                "role": "ERROR",
                "changed": "failed",
                "error": result.stderr[:200] if result.stderr else result.stdout[:200]
            }
        
        try:
            share_result = json.loads(result.stdout)
            share_result["lang"] = lang
            return share_result
        except json.JSONDecodeError:
            return {
                "lang": lang,
                "role": "ERROR",
                "changed": "failed",
                "error": f"Invalid JSON: {result.stdout[:200]}"
            }
    except Exception as e:
        return {
            "lang": lang,
            "role": "ERROR",
            "changed": "failed",
            "error": str(e)[:200]
        }

def main():
    card_id = "6a1d64126a923744238639f9"
    
    # Try to fetch card
    card = None
    
    # First try REST API
    card = fetch_card_via_trello_api(card_id)
    
    # If REST API fails, try to read from stdin (MCP output)
    if not card and len(sys.argv) > 1:
        try:
            card = json.loads(sys.argv[1])
        except json.JSONDecodeError:
            pass
    
    if not card:
        try:
            card = json.load(sys.stdin)
        except:
            pass
    
    if not card:
        print(json.dumps({
            "error": "Could not fetch card 903 - no Trello API credentials found and no stdin/arg provided"
        }))
        sys.exit(1)
    
    description = card.get("desc", "") or ""
    docs = parse_docs_from_description(description)
    
    if not docs:
        print(json.dumps({
            "cardShort": 903,
            "results": [],
            "allWriter": False,
            "problems": ["No Google Docs found in card description"]
        }))
        sys.exit(0)
    
    # Process non-FR docs
    results = []
    problems = []
    all_writer = True
    
    for lang in sorted(docs.keys()):
        if lang == "fr":
            continue  # Skip French
        
        doc_id = docs[lang]
        result = share_doc(doc_id, lang)
        results.append(result)
        
        # Check if role is writer
        role = result.get("role", "ERROR")
        if role != "writer":
            all_writer = False
            if "error" in result:
                problems.append(f"{lang}: {result['error']}")
            else:
                problems.append(f"{lang}: role={role}")
    
    # Final output
    output = {
        "cardShort": 903,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }
    
    print(json.dumps(output, indent=2))

if __name__ == "__main__":
    main()
