#!/usr/bin/env python3
"""
Fetch Trello card #907 and fix Google Docs sharing permissions.
"""
import json
import subprocess
import sys
import os
import re

CARD_ID = "6a1d6422472894ab1927bddf"
CARD_SHORT = 907

def fetch_card_via_api():
    """Try to fetch card via REST API using environment or stored credentials."""
    # Try common credential locations
    creds_file = os.path.expanduser("~/.config/trello.json")
    
    if os.path.exists(creds_file):
        try:
            with open(creds_file) as f:
                creds = json.load(f)
                key = creds.get("key")
                token = creds.get("token")
                
                if key and token:
                    result = subprocess.run([
                        "curl", "-s",
                        f"https://api.trello.com/1/cards/{CARD_ID}?key={key}&token={token}&fields=desc"
                    ], capture_output=True, text=True, timeout=10)
                    
                    try:
                        return json.loads(result.stdout)
                    except:
                        pass
        except:
            pass
    
    return None

def parse_docs_from_description(description):
    """Parse Google Docs from description: lang: https://docs.google.com/document/d/DOC_ID/"""
    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."""
    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",
            "state": "ERR",
            "error": result.stderr[:200] if result.stderr else result.stdout[:200]
        }
    
    try:
        output = json.loads(result.stdout)
        output["lang"] = lang
        return output
    except json.JSONDecodeError:
        return {
            "lang": lang,
            "role": "ERROR",
            "changed": "failed",
            "state": "ERR",
            "error": f"Invalid JSON: {result.stdout[:200]}"
        }

def process_description(description):
    """Process card description and fix permissions."""
    docs = parse_docs_from_description(description)
    
    if not docs:
        return {
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": True,
            "problems": []
        }
    
    results = []
    problems = []
    all_writer = True
    
    for lang in sorted(docs.keys()):
        if lang.lower() == "fr":
            continue  # Skip French
        
        doc_id = docs[lang]
        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.get('error', 'unknown')}")
    
    return {
        "cardShort": CARD_SHORT,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }

def main():
    # Try to read card data from stdin first
    description = None
    
    if len(sys.argv) > 1:
        # Card data passed as argument
        try:
            card_data = json.loads(sys.argv[1])
            description = card_data.get("desc", "")
        except:
            description = sys.argv[1]
    else:
        # Try to read from stdin
        try:
            card_data = json.loads(sys.stdin.read())
            description = card_data.get("desc", "")
        except:
            pass
    
    # If no description from stdin, try API
    if not description:
        card = fetch_card_via_api()
        if card:
            description = card.get("desc", "")
    
    if not description:
        output = {
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["Could not fetch card #907 - no Trello credentials available"]
        }
        print(json.dumps(output, indent=2))
        sys.exit(1)
    
    # Process the description
    output = process_description(description)
    print(json.dumps(output, indent=2))

if __name__ == "__main__":
    main()
