#!/usr/bin/env python3
"""Debug script to investigate order shipping information."""

import sys

sys.path.insert(0, ".")

from app.core.database import SessionLocal
from app.modules.orders.models import Order, OrderItem


def investigate_order(order_number: str):
    """Investigate shipping info for a specific order."""
    db = SessionLocal()
    try:
        # Try to find the order by various number formats
        order = db.query(Order).filter(
            (Order.order_number == order_number) |
            (Order.external_order_number == order_number) |
            (Order.order_number.contains(order_number)) |
            (Order.external_order_number.contains(order_number))
        ).first()

        if not order:
            print(f"Order not found: {order_number}")
            print("\nSearching for similar orders...")
            similar = db.query(Order).filter(
                Order.order_number.ilike(f"%{order_number[-6:]}%")
            ).limit(5).all()
            if similar:
                print("Found similar orders:")
                for o in similar:
                    print(f"  - {o.order_number} (external: {o.external_order_number})")
            return

        print("=" * 60)
        print(f"ORDER FOUND: {order.order_number}")
        print("=" * 60)

        print("\n--- Basic Info ---")
        print(f"  ID: {order.id}")
        print(f"  Order Number: {order.order_number}")
        print(f"  External Order Number: {order.external_order_number}")
        print(f"  External Order ID: {order.external_order_id}")
        print(f"  External Shipment ID: {order.external_shipment_id}")
        print(f"  Channel: {order.channel}")
        print(f"  Status: {order.status}")
        print(f"  Store ID: {order.store_id}")

        print("\n--- Dates ---")
        print(f"  Order Date: {order.order_date}")
        print(f"  Confirmed At: {order.confirmed_at}")
        print(f"  Shipped At: {order.shipped_at}")
        print(f"  Cancelled At: {order.cancelled_at}")
        print(f"  Created At: {order.created_at}")
        print(f"  Updated At: {order.updated_at}")

        print("\n--- Shipping Info ---")
        print(f"  Tracking Number: {order.tracking_number}")
        print(f"  Tracking Provider: {order.tracking_provider}")
        print(f"  Ship First Name: {order.ship_first_name}")
        print(f"  Ship Last Name: {order.ship_last_name}")
        print(f"  Ship Address: {order.ship_address_line_1}")
        print(f"  Ship City: {order.ship_city}")
        print(f"  Ship Postal Code: {order.ship_postal_code}")
        print(f"  Ship Country: {order.ship_country_iso}")

        print("\n--- Customer Info ---")
        print(f"  Customer Name: {order.customer_first_name} {order.customer_last_name}")
        print(f"  Customer Email: {order.customer_email}")

        print("\n--- Financial ---")
        print(f"  Subtotal: {order.subtotal}")
        print(f"  Tax: {order.tax_amount}")
        print(f"  Shipping: {order.shipping_amount}")
        print(f"  Total: {order.total_amount} {order.currency}")

        print("\n--- External Data (raw from Letzshop) ---")
        if order.external_data:
            import json
            # Look for shipping-related fields
            ext = order.external_data
            print(f"  Keys: {list(ext.keys())}")

            # Check for tracking info in external data
            if "tracking" in ext:
                print(f"  tracking: {ext['tracking']}")
            if "trackingNumber" in ext:
                print(f"  trackingNumber: {ext['trackingNumber']}")
            if "carrier" in ext:
                print(f"  carrier: {ext['carrier']}")
            if "state" in ext:
                print(f"  state: {ext['state']}")
            if "shipmentState" in ext:
                print(f"  shipmentState: {ext['shipmentState']}")

            # Print full external data (truncated if too long)
            ext_str = json.dumps(ext, indent=2, default=str)
            if len(ext_str) > 2000:
                print(f"\n  Full data (truncated):\n{ext_str[:2000]}...")
            else:
                print(f"\n  Full data:\n{ext_str}")
        else:
            print("  No external data stored")

        print("\n--- Order Items ---")
        items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
        print(f"  Total items: {len(items)}")
        for i, item in enumerate(items, 1):
            print(f"\n  Item {i}:")
            print(f"    Product: {item.product_name}")
            print(f"    SKU: {item.product_sku}")
            print(f"    GTIN: {item.gtin}")
            print(f"    Qty: {item.quantity}")
            print(f"    Price: {item.unit_price} (total: {item.total_price})")
            print(f"    Item State: {item.item_state}")
            print(f"    External Item ID: {item.external_item_id}")
            print(f"    Needs Product Match: {item.needs_product_match}")

    finally:
        db.close()


if __name__ == "__main__":
    order_number = sys.argv[1] if len(sys.argv) > 1 else "R532332163"
    print(f"Investigating order: {order_number}\n")
    investigate_order(order_number)
