#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test Google Cloud Vision API with service account credentials
"""

import os
from google.cloud import vision

# Set credentials
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'google-credentials.json'

def test_vision_api_sdk(image_path):
    """Test Google Cloud Vision API using official SDK"""

    print(f"\nTesting Google Cloud Vision API on: {image_path}")
    print("="*60)

    try:
        # Initialize the client
        client = vision.ImageAnnotatorClient()

        # Read image
        with open(image_path, 'rb') as image_file:
            content = image_file.read()

        image = vision.Image(content=content)

        # Perform text detection
        response = client.text_detection(image=image)

        if response.error.message:
            print(f"\nAPI Error: {response.error.message}")
            return None

        texts = response.text_annotations

        if texts:
            # First annotation contains all detected text
            full_text = texts[0].description
            print("\n✓ SUCCESS! Google Cloud Vision API is working!")
            print("-"*60)
            print("Full extracted text:")
            print("-"*60)
            print(full_text)
            print("-"*60)

            # Show individual text blocks
            print(f"\nDetected {len(texts)-1} text blocks:")
            for i, text in enumerate(texts[1:6]):  # Show first 5 blocks
                print(f"  {i+1}. {text.description}")

            return full_text
        else:
            print("\nNo text detected")
            return None

    except Exception as e:
        print(f"\nException: {e}")
        import traceback
        traceback.print_exc()
        return None


if __name__ == '__main__':
    import sys

    print("\n" + "="*60)
    print("TESTING GOOGLE CLOUD VISION API WITH SERVICE ACCOUNT")
    print("="*60)

    # Test on cell 12 (which had serial number and profession issues)
    cell_path = 'page3_output/cells/page003_cell12.png'

    if not os.path.exists(cell_path):
        print(f"\nError: Test image not found: {cell_path}")
        print("Please run the extraction pipeline first")
        sys.exit(1)

    result = test_vision_api_sdk(cell_path)

    if result:
        print("\n" + "="*60)
        print("✓ Google Cloud Vision API is WORKING!")
        print("="*60)
        print("\nYou can now use this for better OCR accuracy!")
    else:
        print("\n" + "="*60)
        print("✗ API test failed")
        print("="*60)
        print("\nPossible reasons:")
        print("  - Service account doesn't have Vision API permissions")
        print("  - Vision API not enabled for this project")
        print("  - Billing not set up")
