#!/usr/bin/env python3
"""
Fetch Trello card #904, extract non-FR Google Docs, and fix sharing.
This script orchestrates the MCP fetch + parsing + sharing fix workflow.
"""
import os
import json
import re
import subprocess
import sys

def parse_docs_from_description(description):
    """
    Parse Google Docs from description.
    Expected format: "lang: https://docs.google.com/document/d/DOC_ID/..."
    Returns: dict of lang -> docId
    """
    docs = {}
    if not description:
        return docs

    # Pattern: language (word), colon, URL with /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 the share fix script for a doc.
    Returns: {"role": ..., "changed": ...} or error dict
    """
    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 or result.stdout
        }

    try:
        output = json.loads(result.stdout)
        output["lang"] = lang
        return output
    except json.JSONDecodeError:
        return {
            "lang": lang,
            "role": "ERROR",
            "changed": "failed",
            "error": f"Invalid JSON from share script: {result.stdout}"
        }

def main():
    card_id = "6a1d641621b6ffb7c8481d12"
    
    # The card data should be passed via stdin or argument
    # Try reading from stdin first (for piped MCP output)
    card_data = None
    
    if len(sys.argv) > 1:
        try:
            card_data = json.loads(sys.argv[1])
        except json.JSONDecodeError:
            pass
    
    if not card_data:
        try:
            card_data = json.load(sys.stdin)
        except (json.JSONDecodeError, EOFError):
            # No input provided - card data needs to be fetched via MCP
            print(json.dumps({"error": "Card data not provided - needs to be fetched via MCP tool"}), file=sys.stderr)
            sys.exit(1)
    
    description = card_data.get("desc", "")
    
    # Parse docs
    docs = parse_docs_from_description(description)
    
    if not docs:
        print(json.dumps({"cardShort": 904, "error": "No Google Docs found in card description", "results": [], "allWriter": True, "problems": []}))
        sys.exit(1)
    
    # Process non-FR docs
    results = []
    problems = []
    all_writer = True
    
    for lang, doc_id in sorted(docs.items()):
        if lang.lower() == "fr":
            continue  # Skip French
        
        result = share_doc(doc_id, lang)
        results.append(result)
        
        role = result.get("role", "ERROR")
        if role != "writer":
            all_writer = False
            problems.append(f"{lang}: role={role}")
        
        if result.get("error"):
            problems.append(f"{lang}: {result['error']}")
    
    # Output final result
    output = {
        "cardShort": 904,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }
    
    print(json.dumps(output, indent=2))

if __name__ == "__main__":
    main()

