#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test Google Cloud Vision API with the provided API key
"""

import requests
import base64
import json
import cv2

# API configuration
API_KEY = "AIzaSyDnWU_GLqAKW0Ok6V8IOMt2htk4V7IxU8k"
API_URL = f"https://vision.googleapis.com/v1/images:annotate?key={API_KEY}"

def test_vision_api(image_path):
    """Test Google Cloud Vision API on an image"""

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

    encoded_image = base64.b64encode(image_content).decode('utf-8')

    # Prepare request
    request_body = {
        "requests": [
            {
                "image": {
                    "content": encoded_image
                },
                "features": [
                    {
                        "type": "TEXT_DETECTION"
                    }
                ]
            }
        ]
    }

    # Make API call
    print(f"Testing Google Cloud Vision API on: {image_path}")
    print("="*60)

    try:
        response = requests.post(API_URL, json=request_body, timeout=30)

        print(f"Response status: {response.status_code}")

        if response.status_code == 200:
            result = response.json()

            # Check for errors
            if 'responses' in result and len(result['responses']) > 0:
                response_data = result['responses'][0]

                if 'error' in response_data:
                    print(f"\nAPI Error: {response_data['error']}")
                    return None

                if 'textAnnotations' in response_data:
                    # First annotation is the full text
                    full_text = response_data['textAnnotations'][0]['description']
                    print("\n✓ API WORKS! Extracted text:")
                    print("-"*60)
                    print(full_text)
                    print("-"*60)
                    return full_text
                else:
                    print("\nNo text detected in image")
                    return None
            else:
                print("\nUnexpected response format")
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return None
        else:
            print(f"\nHTTP Error: {response.status_code}")
            print(response.text)
            return None

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


if __name__ == '__main__':
    # Test on cell 12 which had issues
    cell_path = 'page3_output/cells/page003_cell12.png'

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

    result = test_vision_api(cell_path)

    if result:
        print("\n" + "="*60)
        print("SUCCESS: Google Cloud Vision API is working!")
        print("="*60)
    else:
        print("\n" + "="*60)
        print("FAILED: Could not get results from API")
        print("="*60)
        print("\nPossible reasons:")
        print("  - API key is not valid")
        print("  - Cloud Vision API is not enabled for this project")
        print("  - Billing is not set up")
        print("  - API quota exceeded")
