#!/usr/bin/env python3
"""
Check tracking info for a specific shipment from Letzshop API.

Usage:
    python scripts/check_letzshop_tracking.py YOUR_API_KEY SHIPMENT_ID

Example:
    python scripts/check_letzshop_tracking.py abc123 nvDv5RQEmCwbjo
"""

import json
import sys

import requests

ENDPOINT = "https://letzshop.lu/graphql"

# Query with tracking field included
QUERY_SHIPMENT_WITH_TRACKING = """
query GetShipmentsPaginated($first: Int!, $after: String) {
    shipments(state: confirmed, first: $first, after: $after) {
        pageInfo {
            hasNextPage
            endCursor
        }
        nodes {
            id
            number
            state
            tracking {
                number
                url
                carrier {
                    name
                    code
                }
            }
            order {
                id
                number
                email
                total
            }
            inventoryUnits {
                id
                state
            }
        }
    }
}
"""


def get_tracking_info(api_key: str, target_shipment_id: str):
    """Get tracking info for a specific shipment."""

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    }

    print(f"Looking for shipment: {target_shipment_id}")
    print("=" * 60)

    # Paginate through confirmed shipments
    has_next = True
    after = None
    page = 0

    while has_next and page < 20:
        page += 1
        variables = {"first": 50, "after": after}

        response = requests.post(
            ENDPOINT,
            headers=headers,
            json={"query": QUERY_SHIPMENT_WITH_TRACKING, "variables": variables},
        )

        if response.status_code != 200:
            print(f"Error: HTTP {response.status_code}")
            print(response.text)
            return None

        data = response.json()

        if "errors" in data:
            print(f"GraphQL errors: {json.dumps(data['errors'], indent=2)}")
            return None

        result = data.get("data", {}).get("shipments", {})
        nodes = result.get("nodes", [])
        page_info = result.get("pageInfo", {})

        print(f"Page {page}: {len(nodes)} shipments")

        for shipment in nodes:
            if shipment.get("id") == target_shipment_id:
                print(f"\n{'=' * 60}")
                print("FOUND SHIPMENT!")
                print(f"{'=' * 60}")

                print("\n--- Shipment Info ---")
                print(f"  ID: {shipment.get('id')}")
                print(f"  Number: {shipment.get('number')}")
                print(f"  State: {shipment.get('state')}")

                print("\n--- Tracking Info ---")
                tracking = shipment.get("tracking")
                if tracking:
                    print(f"  Tracking Number: {tracking.get('number')}")
                    print(f"  Tracking URL: {tracking.get('url')}")
                    carrier = tracking.get("carrier", {})
                    if carrier:
                        print(f"  Carrier Name: {carrier.get('name')}")
                        print(f"  Carrier Code: {carrier.get('code')}")
                else:
                    print("  No tracking object returned")

                print("\n--- Order Info ---")
                order = shipment.get("order", {})
                print(f"  Order Number: {order.get('number')}")
                print(f"  Email: {order.get('email')}")

                print("\n--- Raw Response ---")
                print(json.dumps(shipment, indent=2, default=str))
                return shipment

        has_next = page_info.get("hasNextPage", False)
        after = page_info.get("endCursor")

    print(f"\nShipment {target_shipment_id} not found in confirmed shipments")
    return None


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python scripts/check_letzshop_tracking.py YOUR_API_KEY SHIPMENT_ID")
        print("\nExample:")
        print("  python scripts/check_letzshop_tracking.py abc123 nvDv5RQEmCwbjo")
        sys.exit(1)

    api_key = sys.argv[1]
    shipment_id = sys.argv[2]

    get_tracking_info(api_key, shipment_id)
