#! /usr/bin/env python3
import argparse
import sys
import logging
import subprocess
import requests
import json

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="trello-dump-card", description="Dump a Trello card for debugging"
    )
    ap.add_argument("card_short_link", help="Trello card short link")
    ap.add_argument("--board", help="Trello board ID", default="tw3Cn3L6")
    ap.add_argument(
        "-v", "--verbose", help="Enable verbose logging", action="store_true"
    )
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s:	%(message)s",
    )

    # Read API credentials
    trello_api_key = subprocess.check_output(
        "op read -n 'op://ewconfig/cbnd5vv3germmc4korkxx3nsim/api key'", shell=True
    ).decode()
    trello_api_token = subprocess.check_output(
        "op read -n 'op://ewconfig/cbnd5vv3germmc4korkxx3nsim/credential'",
        shell=True,
    ).decode()

    # Get all cards
    response = requests.get(
        f"https://api.trello.com/1/boards/{args.board}/cards",
        params={
            "key": trello_api_key,
            "token": trello_api_token,
        },
    )
    response.raise_for_status()
    cards = response.json()

    # Find the card
    card = next(
        (card for card in cards if card["shortLink"] == args.card_short_link), None
    )

    # If no card was found, fail
    if not card:
        logger.error(f"Card {args.card_short_link} not found")
        return 1

    # Dump the card
    print(json.dumps(card, indent=4))

    return 0


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