import requests
import json
import sys
import os

def test_ocr(image_path):
    url = "http://localhost:8000/api/ocr/cccd"
    
    if not os.path.exists(image_path):
        print(f"Lỗi: Không tìm thấy file ảnh tại {image_path}")
        return
        
    print(f"Đang gửi ảnh {image_path} đến API OCR...")
    
    with open(image_path, 'rb') as f:
        files = {'file': (os.path.basename(image_path), f, 'image/jpeg')}
        try:
            response = requests.post(url, files=files)
            print(f"HTTP Status Code: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print("\nKết quả OCR thành công:")
                print(json.dumps(result["data"], indent=4, ensure_ascii=False))
                print(f"\nThời gian xử lý của API: {result['processing_time_sec']} giây")
                print(f"Có cắt thẳng ảnh không: {result['is_warped']}")
            else:
                print("Lỗi từ API:")
                print(response.text)
        except requests.exceptions.ConnectionError:
            print("Lỗi: Không thể kết nối tới API. Hãy chắc chắn uvicorn đang chạy trên cổng 8000.")
        except Exception as e:
            print(f"Có lỗi xảy ra: {e}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Cách dùng: ./venv/bin/python test_api.py <đường_dẫn_ảnh_cccd>")
        sys.exit(1)
        
    test_ocr(sys.argv[1])
