#!/usr/bin/env python3
"""
Orchestrate the Trello card #909 fix.
This will:
1. Fetch card data (simulate via known structure)
2. Parse description for lang->docId mapping
3. Call _share_fix.py share for each non-FR language
4. Return structured results
"""
import json
import subprocess
import sys
import re
from pathlib import Path

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

def parse_card_description(desc):
    """
    Parse description to extract lang -> docId mapping.
    Format: "en: https://docs.google.com/document/d/<docId>/..."
    """
    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 ""
        
        # Extract docId from URL
        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 <docId>"""
    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]}
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError:
        return {"ok": False, "error": f"Invalid JSON: {result.stdout[:200]}"}

def main():
    # This would be populated from the actual Trello card fetch
    # For now, we'll document the expected structure
    
    # In real usage, the card description would be fetched via mcp__trello__get_card
    # and passed here. For demonstration:
    
    card_data = {
        "id": "6a1d692c59da8676881ec337",
        "name": "CINIK #909 - Document sharing",
        "description": """
en: https://docs.google.com/document/d/EN_DOC_ID_1/edit
it: https://docs.google.com/document/d/IT_DOC_ID_2/edit
de: https://docs.google.com/document/d/DE_DOC_ID_3/edit
fr: https://docs.google.com/document/d/FR_DOC_ID/edit
"""
    }
    
    # Parse the description
    langs_docs = parse_card_description(card_data["description"])
    print(f"Parsed languages: {list(langs_docs.keys())}", file=sys.stderr)
    
    results = []
    all_writer = True
    problems = []
    
    for lang, doc_id in sorted(langs_docs.items()):
        if lang == "fr":
            print(f"Skipping FR doc", file=sys.stderr)
            continue
        
        print(f"Processing {lang}: {doc_id}...", file=sys.stderr)
        share_result = share_doc(doc_id)
        
        result_entry = {
            "lang": lang,
            "role": share_result.get("role", "unknown"),
            "changed": share_result.get("changed", "error")
        }
        results.append(result_entry)
        
        if not share_result.get("ok", False):
            all_writer = False
            problems.append(lang)
    
    output = {
        "cardShort": 909,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }
    
    print(json.dumps(output, indent=2))
    return 0 if all_writer else 1

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