#!/usr/bin/env python3
"""
Direct call to fetch card #893 data and execute the permission fix.
This will use the MCP Trello integration if available, or fall back to manual API call.
"""

import json
import subprocess
import sys
import os

# Card ID for CINIK blog pipeline
CARD_ID = "69ea1e5568694218e3b95b60"
CARD_SHORT = 893
HELPER = "/opt/automator/cinik-writer-transtor/files/_share_fix.py"

def get_trello_credentials():
    """Try to get Trello API credentials."""
    # Check environment
    key = os.environ.get("TRELLO_KEY")
    token = os.environ.get("TRELLO_TOKEN")
    
    if key and token:
        return key, token
    
    # Try to find in config
    config_paths = [
        "/home/dev/.trello-mcp/credentials.json",
        "/home/dev/.config/trello/credentials.json",
    ]
    
    for path in config_paths:
        if os.path.exists(path):
            try:
                with open(path) as f:
                    creds = json.load(f)
                    return creds.get("key"), creds.get("token")
            except:
                pass
    
    return None, None

def fetch_card_via_api(card_id, key=None, token=None):
    """Fetch card via Trello API."""
    url = f"https://api.trello.com/1/cards/{card_id}"
    
    params = {}
    if key and token:
        params["key"] = key
        params["token"] = token
    
    # Build URL with params
    if params:
        param_str = "&".join(f"{k}={v}" for k, v in params.items())
        url = f"{url}?{param_str}"
    
    try:
        result = subprocess.run(
            ["curl", "-s", url],
            capture_output=True,
            text=True,
            timeout=10
        )
        
        if result.returncode == 0:
            data = json.loads(result.stdout)
            return data
    except:
        pass
    
    return None

def parse_description(desc):
    """Extract language -> 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)
        if len(parts) != 2:
            continue
        
        lang = parts[0].strip().lower()
        url_part = parts[1].strip()
        
        if 'docs.google.com/document/d/' in url_part:
            try:
                doc_id = url_part.split('/d/')[1].split('/')[0]
                if doc_id:
                    mapping[lang] = doc_id
            except:
                pass
    
    return mapping

def share_doc(doc_id):
    """Call _share_fix.py share <docId>."""
    if not doc_id:
        return {"ok": False, "state": "NO-ID", "role": None, "changed": None}
    
    try:
        result = subprocess.run(
            [sys.executable, HELPER, "share", doc_id],
            capture_output=True,
            text=True,
            timeout=30,
        )
        
        if result.returncode == 0:
            try:
                return json.loads(result.stdout)
            except:
                return {
                    "ok": False,
                    "state": "PARSE_ERROR",
                    "role": None,
                    "changed": None,
                }
        else:
            return {
                "ok": False,
                "state": "EXEC_ERROR",
                "role": None,
                "changed": None,
                "stderr": result.stderr[:200],
            }
    except Exception as e:
        return {
            "ok": False,
            "state": "ERROR",
            "role": None,
            "changed": None,
        }

def main():
    """Main entry point."""
    
    # Try to fetch card
    key, token = get_trello_credentials()
    card_data = fetch_card_via_api(CARD_ID, key, token)
    
    if not card_data:
        print(json.dumps({
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["Failed to fetch card from Trello API"],
        }))
        return 1
    
    # Extract description
    description = card_data.get("desc", "")
    
    if not description:
        print(json.dumps({
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["Card has no description"],
        }))
        return 1
    
    # Parse languages and doc IDs
    langs = parse_description(description)
    
    if not langs:
        print(json.dumps({
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["No Google Docs found in description"],
        }))
        return 1
    
    # Process each non-FR language
    results = []
    problems = []
    all_writer = True
    
    for lang in sorted(langs.keys()):
        if lang.lower() == 'fr':
            continue  # Skip French
        
        doc_id = langs[lang]
        share_result = share_doc(doc_id)
        
        result_obj = {
            "lang": lang,
            "role": share_result.get("role"),
            "changed": share_result.get("changed"),
        }
        results.append(result_obj)
        
        # Track issues
        if not share_result.get("ok"):
            all_writer = False
            problems.append(lang)
        elif share_result.get("role") != "writer":
            all_writer = False
            problems.append(lang)
    
    # Return structured output
    output = {
        "cardShort": CARD_SHORT,
        "results": results,
        "allWriter": all_writer,
        "problems": problems,
    }
    
    print(json.dumps(output, indent=2, ensure_ascii=False))
    return 0 if all_writer else 1

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