#!/usr/bin/env python3
"""
Card #918 permission fixer.
This script will be called with the card description from Trello.
"""
import json
import subprocess
import sys
import os
from pathlib import Path
from typing import Dict, List, Any

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

def parse_card_description(desc: str) -> Dict[str, str]:
    """
    Parse Trello card description to extract lang -> docId mapping.

    Expected format:
        en: https://docs.google.com/document/d/EN_DOC_ID/edit
        it: https://docs.google.com/document/d/IT_DOC_ID/edit
        ...
    """
    mapping = {}
    if not desc:
        return mapping

    for line in desc.split('\n'):
        line = line.strip()
        if not line or ':' not in line:
            continue

        # Split on first colon
        parts = line.split(':', 1)
        if len(parts) != 2:
            continue

        lang = parts[0].strip().lower()
        url_part = parts[1].strip()

        # Extract docId from Google Docs URL
        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 (IndexError, ValueError):
                pass

    return mapping

def share_doc(doc_id: str) -> Dict[str, Any]:
    """
    Call _share_fix.py share <docId> 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:
            stderr = result.stderr[:200] if result.stderr else "Unknown error"
            return {"ok": False, "changed": "error", "error": stderr, "role": None}

        try:
            return json.loads(result.stdout)
        except json.JSONDecodeError:
            return {"ok": False, "changed": "error", "error": f"Invalid JSON: {result.stdout[:100]}", "role": None}

    except subprocess.TimeoutExpired:
        return {"ok": False, "changed": "error", "error": "Timeout", "role": None}
    except Exception as e:
        return {"ok": False, "changed": "error", "error": str(e)[:200], "role": None}

def process_card_description(description: str, card_number: int = CARD_SHORT) -> Dict[str, Any]:
    """
    Main processing function: parse description and share all non-FR docs.
    """
    # Parse languages and doc IDs
    langs_docs = parse_card_description(description)

    if not langs_docs:
        return {
            "cardShort": card_number,
            "results": [],
            "allWriter": False,
            "problems": ["no_docs_found"]
        }

    results: List[Dict[str, Any]] = []
    all_writer = True
    problems: List[str] = []

    # Process each language except FR
    for lang in sorted(langs_docs.keys()):
        if lang.lower() == "fr":
            continue

        doc_id = langs_docs[lang]
        share_result = share_doc(doc_id)

        # Build result entry
        result_entry = {
            "lang": lang,
            "role": share_result.get("role"),
            "changed": share_result.get("changed", "error")
        }
        results.append(result_entry)

        # Track overall state
        if share_result.get("role") != "writer":
            all_writer = False

        if not share_result.get("ok"):
            problems.append(lang)

    return {
        "cardShort": card_number,
        "results": results,
        "allWriter": all_writer,
        "problems": problems
    }

def main():
    """
    Main entry point.
    """
    card_description = None

    # Try command-line argument first
    if len(sys.argv) > 1:
        card_description = sys.argv[1]

    # Try stdin if no argument
    if not card_description:
        try:
            card_description = sys.stdin.read().strip()
        except:
            pass

    # If still no data, error
    if not card_description:
        output = {
            "cardShort": CARD_SHORT,
            "results": [],
            "allWriter": False,
            "problems": ["no_card_description_provided"]
        }
        print(json.dumps(output, indent=2))
        return 1

    # Process the card
    output = process_card_description(card_description, CARD_SHORT)
    print(json.dumps(output, indent=2))
    return 0 if not output["problems"] else 1

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