#!/usr/bin/env python3
"""
Orchestrator for Trello Card #912 fix.
Since MCP tools require special handling, this script simulates the full workflow
by accepting the card description as input.
"""
import json
import subprocess
import sys
from pathlib import Path

CARD_ID = "6a1d693a13ab4ec5a2840f47"
CARD_SHORT = 912
EXECUTE_SCRIPT = Path("/opt/automator/cinik-writer-transtor/files/execute_card_912_fix.py")

def main():
    """
    Main flow:
    1. If card_description is passed as arg, use it
    2. Otherwise, indicate that MCP fetch is needed
    3. Call execute_card_912_fix.py with description
    4. Return structured result
    """
    card_description = None
    
    # Check if description was passed via CLI or env
    if len(sys.argv) > 1:
        card_description = sys.argv[1]
    
    # Check env var
    if not card_description:
        card_description = __import__('os').environ.get('CARD_912_DESC')
    
    # If we have the description, process it
    if card_description:
        result = subprocess.run(
            [sys.executable, str(EXECUTE_SCRIPT), card_description],
            capture_output=True,
            text=True,
            timeout=120
        )
        
        if result.returncode == 0 or result.stdout.strip():
            try:
                output = json.loads(result.stdout)
                print(json.dumps(output, indent=2))
            except:
                print(result.stdout)
        else:
            print(f"ERROR: {result.stderr}", file=sys.stderr)
            sys.exit(1)
    else:
        # Need MCP card fetch
        output = {
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["requires_mcp_fetch"],
            "note": f"Please fetch card {CARD_ID} via mcp__trello__get_card and pass description"
        }
        print(json.dumps(output, indent=2), file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
