"""
Manual test for V2 API integration with Celery.

This test verifies that:
1. The API endpoint triggers the V2 extraction task
2. The V2 task processes files correctly
3. V1 fallback works when V2 fails

Run this test manually after starting the API server and Celery worker:
    Terminal 1: uv run uvicorn src.api.main:app --reload
    Terminal 2: uv run celery -A src.workers.celery_app worker --loglevel=info
    Terminal 3: uv run python tests/manual/test_v2_api_integration.py
"""

import sys
from pathlib import Path
from uuid import uuid4

# Add project root to path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))


def test_v2_pipeline_direct():
    """Test V2 pipeline directly (without API/Celery)."""
    from src.extraction_v2.pipeline import ExtractionPipelineV2

    print("\n" + "="*80)
    print("TEST 1: Direct V2 Pipeline Test")
    print("="*80)

    # Get test file path
    test_file = project_root / "tests" / "fixtures" / "customer_docs" / "example.xlsx"

    if not test_file.exists():
        print(f"❌ Test file not found: {test_file}")
        print("   Please provide a test Excel file")
        return False

    print(f"\nTest file: {test_file}")
    print(f"File exists: {test_file.exists()}")

    # Create pipeline and process
    pipeline = ExtractionPipelineV2()
    doc_id = uuid4()

    print(f"\nProcessing document {doc_id}...")
    result = pipeline.process_document_sync(doc_id, str(test_file))

    # Print results
    print("\n" + "-"*80)
    print(f"Success: {result.success}")
    if result.success:
        print(f"✅ V2 Pipeline succeeded!")
        print(f"   Tables: {result.table_count}")
        print(f"   Records: {result.record_count}")

        # Show first record
        if result.records:
            print(f"\n   First record sample:")
            first_record = result.records[0]
            print(f"   Content keys: {list(first_record.get('content', {}).keys())}")
            print(f"   Source: {first_record.get('_source', {})}")
    else:
        print(f"❌ V2 Pipeline failed: {result.error}")

    print("-"*80)
    return result.success


def test_v2_celery_task():
    """Test V2 Celery task directly (without API)."""
    from src.workers.extraction_v2_tasks import extract_document_v2

    print("\n" + "="*80)
    print("TEST 2: V2 Celery Task Test (Direct Call)")
    print("="*80)

    # Get test file path
    test_file = project_root / "tests" / "fixtures" / "customer_docs" / "example.xlsx"

    if not test_file.exists():
        print(f"❌ Test file not found: {test_file}")
        return False

    doc_id = str(uuid4())

    print(f"\nDocument ID: {doc_id}")
    print(f"File path: {test_file}")

    # Call task directly (synchronous, not via Celery worker)
    print("\nCalling extract_document_v2 task directly...")
    try:
        result = extract_document_v2(doc_id, str(test_file))

        print("\n" + "-"*80)
        print(f"Status: {result.get('status')}")
        print(f"Pipeline: {result.get('pipeline')}")
        print(f"Records: {result.get('record_count', 0)}")
        print(f"Tables: {result.get('table_count', 0)}")

        if result.get('fallback_reason'):
            print(f"⚠️  Fallback used: {result.get('fallback_reason')}")

        if result.get('status') == 'success':
            print(f"✅ Task completed successfully!")
        else:
            print(f"❌ Task failed")

        print("-"*80)
        return result.get('status') == 'success'

    except Exception as e:
        print(f"\n❌ Task failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_api_upload():
    """Test API endpoint upload (requires running API server)."""
    import requests

    print("\n" + "="*80)
    print("TEST 3: API Upload Test")
    print("="*80)
    print("NOTE: This test requires:")
    print("  1. API server running: uv run uvicorn src.api.main:app --reload")
    print("  2. Celery worker running: uv run celery -A src.workers.celery_app worker")
    print("  3. Valid API key in database")
    print("="*80)

    # Test file
    test_file = project_root / "tests" / "fixtures" / "customer_docs" / "example.xlsx"

    if not test_file.exists():
        print(f"❌ Test file not found: {test_file}")
        return False

    # API configuration (update with your actual values)
    API_BASE_URL = "http://localhost:8000"
    API_KEY = "test-api-key"  # Replace with actual API key

    print(f"\nAPI URL: {API_BASE_URL}")
    print(f"API Key: {API_KEY[:8]}..." if len(API_KEY) > 8 else API_KEY)

    # Upload file
    print(f"\nUploading file: {test_file.name}")

    try:
        with open(test_file, 'rb') as f:
            files = {'file': (test_file.name, f, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')}
            headers = {'X-API-Key': API_KEY}

            response = requests.post(
                f"{API_BASE_URL}/api/v1/documents",
                files=files,
                headers=headers,
                timeout=30
            )

        print(f"\nResponse status: {response.status_code}")
        print(f"Response body: {response.json()}")

        if response.status_code == 202:
            print(f"✅ Document uploaded successfully!")
            document_id = response.json().get('document_id')
            print(f"   Document ID: {document_id}")
            print(f"\n   Check status with:")
            print(f"   curl -H 'X-API-Key: {API_KEY}' {API_BASE_URL}/api/v1/documents/{document_id}")
            return True
        else:
            print(f"❌ Upload failed")
            return False

    except requests.exceptions.ConnectionError:
        print(f"\n❌ Could not connect to API server at {API_BASE_URL}")
        print(f"   Please start the API server first:")
        print(f"   uv run uvicorn src.api.main:app --reload")
        return False
    except Exception as e:
        print(f"\n❌ API test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all tests."""
    print("\n")
    print("╔" + "="*78 + "╗")
    print("║" + " "*20 + "V2 API INTEGRATION TEST SUITE" + " "*28 + "║")
    print("╚" + "="*78 + "╝")

    results = []

    # Test 1: Direct V2 pipeline
    try:
        results.append(("Direct V2 Pipeline", test_v2_pipeline_direct()))
    except Exception as e:
        print(f"\n❌ Test 1 crashed: {e}")
        results.append(("Direct V2 Pipeline", False))

    # Test 2: Celery task (direct call)
    try:
        results.append(("V2 Celery Task", test_v2_celery_task()))
    except Exception as e:
        print(f"\n❌ Test 2 crashed: {e}")
        results.append(("V2 Celery Task", False))

    # Test 3: API upload (optional - requires running server)
    skip_api_test = input("\n\nRun API test? (requires running API server) [y/N]: ")
    if skip_api_test.lower() == 'y':
        try:
            results.append(("API Upload", test_api_upload()))
        except Exception as e:
            print(f"\n❌ Test 3 crashed: {e}")
            results.append(("API Upload", False))
    else:
        print("\nSkipping API test")
        results.append(("API Upload", None))

    # Summary
    print("\n")
    print("╔" + "="*78 + "╗")
    print("║" + " "*30 + "TEST SUMMARY" + " "*36 + "║")
    print("╚" + "="*78 + "╝")
    print()

    for test_name, passed in results:
        if passed is None:
            status = "⊘  SKIPPED"
        elif passed:
            status = "✅ PASSED"
        else:
            status = "❌ FAILED"
        print(f"  {status}  {test_name}")

    print("\n" + "="*80 + "\n")

    # Exit code
    failed_count = sum(1 for _, passed in results if passed is False)
    if failed_count > 0:
        print(f"❌ {failed_count} test(s) failed")
        sys.exit(1)
    else:
        print(f"✅ All tests passed!")
        sys.exit(0)


if __name__ == "__main__":
    main()
