#!/usr/bin/env python3
"""
Complete orchestration for Trello card #909 permission fix.

This script:
1. Would fetch card via mcp__trello__get_card (requires Claude Code integration)
2. Parses the description for lang->docId mapping
3. Calls _share_fix.py share for each non-FR language
4. Returns StructuredOutput format

Since we're in Claude Code with MCP loaded, the fetch happens via the tool itself.
This script handles parsing and the remediation loop.
"""
import json
import subprocess
import sys
import re
from pathlib import Path

HELPER = Path("/opt/automator/cinik-writer-transtor/files/_share_fix.py")
CARD_ID = "6a1d692c59da8676881ec337"

def parse_card_description(desc):
    """Parse description for lang -> docId mapping"""
    mapping = {}
    if not desc:
        return mapping
    
    for line in desc.split('\n'):
        line = line.strip()
        if not line or ':' not in line:
            continue
        
        parts = line.split(':', 1)
        lang = parts[0].strip().lower()
        url_part = parts[1].strip() if len(parts) > 1 else ""
        
        if 'docs.google.com/document/d/' in url_part:
            try:
                doc_id = url_part.split('/d/')[1].split('/')[0]
                mapping[lang] = doc_id
            except IndexError:
                pass
    
    return mapping

def share_doc(doc_id):
    """Call _share_fix.py share and return result"""
    try:
        result = subprocess.run(
            [sys.executable, str(HELPER), "share", doc_id],
            capture_output=True,
            text=True,
            timeout=30
        )
        if result.returncode != 0:
            return {"ok": False, "error": result.stderr[:200]}
        return json.loads(result.stdout)
    except Exception as e:
        return {"ok": False, "error": str(e)[:200]}

def process_card(card_description):
    """Process a card's non-FR docs and return results"""
    langs_docs = parse_card_description(card_description)
    
    results = []
    all_writer = True
    problems = []
    
    # Sort to process consistently
    for lang in sorted(langs_docs.keys()):
        if lang == "fr":
            continue
        
        doc_id = langs_docs[lang]
        share_result = share_doc(doc_id)
        
        result_entry = {
            "lang": lang,
            "role": share_result.get("role"),
            "changed": share_result.get("changed")
        }
        results.append(result_entry)
        
        if share_result.get("role") != "writer":
            all_writer = False
        
        if not share_result.get("ok"):
            problems.append(lang)
    
    return {
        "cardShort": 909,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }

# Main: when called from Claude Code with card data
if __name__ == "__main__":
    if len(sys.argv) > 1:
        card_desc = sys.argv[1]
        output = process_card(card_desc)
        print(json.dumps(output, indent=2))
    else:
        print("Usage: orchestrate_card_909.py '<card_description>'", file=sys.stderr)
        print("Card description should contain lines: 'lang: https://docs.google.com/document/d/<id>/...'", file=sys.stderr)
        sys.exit(1)
