#!/usr/bin/env python3
"""Debug script for historical import issues."""

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

from app.core.database import SessionLocal
from app.services.letzshop.credentials_service import LetzshopCredentialsService
from models.database.letzshop import LetzshopHistoricalImportJob


def get_valid_shipment_states(vendor_id: int = 1):
    """Query the GraphQL schema to find valid ShipmentStateEnum values."""
    db = SessionLocal()
    try:
        creds_service = LetzshopCredentialsService(db)

        # Introspection query to get enum values
        introspection_query = """
        query {
            __type(name: "ShipmentStateEnum") {
                name
                enumValues {
                    name
                    description
                }
            }
        }
        """

        with creds_service.create_client(vendor_id) as client:
            print("Querying ShipmentStateEnum values...")
            result = client._execute(introspection_query)

            if result and "__type" in result:
                type_info = result["__type"]
                if type_info:
                    print(f"\nEnum: {type_info['name']}")
                    print("Valid values:")
                    for value in type_info.get("enumValues", []):
                        print(f"  - {value['name']}: {value.get('description', 'No description')}")
                else:
                    print("ShipmentStateEnum type not found")
            else:
                print(f"Unexpected result: {result}")

    finally:
        db.close()


def check_import_job_status():
    """Check the status of historical import jobs."""
    db = SessionLocal()
    try:
        jobs = db.query(LetzshopHistoricalImportJob).order_by(
            LetzshopHistoricalImportJob.id.desc()
        ).limit(5).all()

        print("\n=== Recent Historical Import Jobs ===")
        for job in jobs:
            print(f"\nJob {job.id}:")
            print(f"  Status: {job.status}")
            print(f"  Phase: {job.current_phase}")
            print(f"  Page: {job.current_page}")
            print(f"  Shipments fetched: {job.shipments_fetched}")
            print(f"  Orders processed: {job.orders_processed}")
            print(f"  Orders imported: {job.orders_imported}")
            print(f"  Orders updated: {job.orders_updated}")
            print(f"  Orders skipped: {job.orders_skipped}")
            print(f"  Confirmed stats: {job.confirmed_stats}")
            print(f"  Declined stats: {job.declined_stats}")
            print(f"  Error: {job.error_message}")
            print(f"  Started: {job.started_at}")
            print(f"  Completed: {job.completed_at}")
    finally:
        db.close()


def test_fetch_states(vendor_id: int = 1):
    """Test fetching shipments with different states."""
    db = SessionLocal()
    try:
        creds_service = LetzshopCredentialsService(db)

        # States to test
        states_to_test = ["unconfirmed", "confirmed", "declined", "shipped", "rejected"]

        with creds_service.create_client(vendor_id) as client:
            for state in states_to_test:
                print(f"\nTesting state: {state}")
                try:
                    # Just try to fetch first page
                    shipments = client.get_all_shipments_paginated(
                        state=state,
                        page_size=1,
                        max_pages=1,
                    )
                    print(f"  ✓ Success: {len(shipments)} shipments")
                except Exception as e:
                    print(f"  ✗ Error: {e}")

    finally:
        db.close()


def check_declined_items(vendor_id: int = 1):
    """Check for orders with declined inventory units."""
    db = SessionLocal()
    try:
        from models.database.letzshop import LetzshopOrder
        from collections import Counter

        # Get all orders with inventory_units
        orders = db.query(LetzshopOrder).filter(
            LetzshopOrder.vendor_id == vendor_id,
            LetzshopOrder.inventory_units.isnot(None),
        ).all()

        # Count all states
        state_counts = Counter()
        total_units = 0

        for order in orders:
            units = order.inventory_units or []
            for unit in units:
                state = unit.get("state", "unknown")
                state_counts[state] += 1
                total_units += 1

        print(f"\n=== Inventory Unit States (all {len(orders)} orders) ===")
        print(f"  Total units: {total_units}")
        print(f"\n  State breakdown:")
        for state, count in sorted(state_counts.items(), key=lambda x: -x[1]):
            print(f"    {state}: {count}")

        # Show a sample order with its units
        if orders:
            sample = orders[0]
            print(f"\nSample order #{sample.id} (shipment {sample.letzshop_shipment_id}):")
            print(f"  Shipment state: {sample.letzshop_state}")
            print(f"  Sync status: {sample.sync_status}")
            if sample.inventory_units:
                for i, unit in enumerate(sample.inventory_units[:5]):
                    print(f"  Unit {i+1}: state={unit.get('state')}, id={unit.get('id')}")

    finally:
        db.close()


if __name__ == "__main__":
    print("=== Letzshop Historical Import Debug ===\n")

    print("1. Checking valid shipment states...")
    get_valid_shipment_states()

    print("\n\n2. Testing different state values...")
    test_fetch_states()

    print("\n\n3. Checking import job status...")
    check_import_job_status()

    print("\n\n4. Checking declined items in inventory units...")
    check_declined_items()
