#!/usr/bin/env python3
"""
Final orchestrator for Card #903 sharing permission fix.
This script:
1. Tries to fetch card #903 via multiple methods
2. Parses the description
3. Runs sharing fix for all non-FR docs
4. Returns structured output
"""
import json
import subprocess
import sys
import os
import re

CARD_ID = "6a1d64126a923744238639f9"
SHARE_FIX_PATH = "/opt/automator/cinik-writer-transtor/files/_share_fix.py"
EXECUTE_FIX_PATH = "/opt/automator/cinik-writer-transtor/files/EXECUTE_CARD_903_FIX.py"

def fetch_card_data():
    """Try multiple methods to fetch card #903."""
    
    # Method 1: Try REST API with environment credentials
    api_key = os.environ.get('TRELLO_API_KEY') or os.environ.get('TRELLO_KEY')
    api_token = os.environ.get('TRELLO_API_TOKEN') or os.environ.get('TRELLO_TOKEN')
    
    if api_key and api_token:
        try:
            import urllib.request
            url = f"https://api.trello.com/1/cards/{CARD_ID}?key={api_key}&token={api_token}&fields=desc,name"
            with urllib.request.urlopen(url, timeout=10) as response:
                return json.loads(response.read().decode())
        except Exception as e:
            print(f"WARNING: REST API failed: {e}", file=sys.stderr)
    
    # Method 2: Check stdin for card data
    try:
        card_data = sys.stdin.read().strip()
        if card_data.startswith('{'):
            return json.loads(card_data)
    except:
        pass
    
    # Method 3: Check for cached card data
    cache_file = f"/tmp/card_{CARD_ID}.json"
    if os.path.exists(cache_file):
        try:
            with open(cache_file) as f:
                return json.load(f)
        except:
            pass
    
    return None

def run_fixer(description):
    """Run the EXECUTE_CARD_903_FIX.py script with the description."""
    result = subprocess.run(
        [sys.executable, EXECUTE_FIX_PATH, description],
        capture_output=True,
        text=True,
        timeout=120
    )
    
    if result.returncode == 0:
        try:
            return json.loads(result.stdout)
        except Exception as e:
            return {
                "cardShort": 903,
                "results": [],
                "allWriter": False,
                "problems": [f"JSON_PARSE_ERROR: {str(e)[:100]}"]
            }
    else:
        stderr = result.stderr if result.stderr else result.stdout
        return {
            "cardShort": 903,
            "results": [],
            "allWriter": False,
            "problems": [f"FIXER_ERROR: {stderr[:200]}"]
        }

def main():
    # Fetch card data
    card = fetch_card_data()
    
    if not card:
        output = {
            "cardShort": 903,
            "results": [],
            "allWriter": False,
            "problems": [
                "FAILED_TO_FETCH_CARD: No Trello API credentials, no stdin data, and no cached card"
            ]
        }
        print(json.dumps(output, indent=2))
        return 1
    
    # Extract description
    description = card.get('desc', '') or ''
    
    if not description:
        output = {
            "cardShort": 903,
            "results": [],
            "allWriter": False,
            "problems": ["EMPTY_DESCRIPTION"]
        }
        print(json.dumps(output, indent=2))
        return 0
    
    # Run the fixer
    output = run_fixer(description)
    print(json.dumps(output, indent=2))
    
    return 0 if output.get("allWriter") else 1

if __name__ == "__main__":
    sys.exit(main())
