#!/usr/bin/env python3
"""
Test script for File Watcher Service
Tests the PDF extraction and Odoo sync functionality
"""

import json
import sys
from pathlib import Path
from file_watcher_service import PDFDataExtractor, OdooClient, load_config

def test_pdf_extraction(pdf_path):
    """Test extracting data from a PDF"""
    print(f"\n=== Testing PDF Extraction ===")
    print(f"PDF: {pdf_path}")
    
    extractor = PDFDataExtractor()
    data = extractor.extract_from_pdf(pdf_path)
    
    if data:
        print(f"Extracted {len(data)} fields:")
        for field, value in data.items():
            print(f"  {field}: {value}")
    else:
        print("No data extracted")
    
    return data

def test_odoo_connection():
    """Test Odoo connection"""
    print("\n=== Testing Odoo Connection ===")
    
    odoo_config, _ = load_config()
    client = OdooClient(odoo_config)
    
    if client.connect():
        print("✓ Successfully connected to Odoo")
        return client
    else:
        print("✗ Failed to connect to Odoo")
        return None

def test_lead_search(client, phone):
    """Test searching for leads"""
    print(f"\n=== Testing Lead Search ===")
    print(f"Phone: {phone}")
    
    leads = client.search_leads_by_phone(phone)
    
    if leads:
        print(f"Found {len(leads)} leads:")
        for lead in leads:
            print(f"  - {lead['name']} (ID: {lead['id']})")
            if lead.get('tags'):
                print(f"    Tags: {', '.join(lead['tags'])}")
    else:
        print("No leads found")
    
    return leads

def main():
    """Run tests"""
    print("File Watcher Service Test")
    print("=" * 50)
    
    # Test with a sample PDF if provided
    if len(sys.argv) > 1:
        pdf_path = sys.argv[1]
        if not Path(pdf_path).exists():
            print(f"Error: File not found: {pdf_path}")
            sys.exit(1)
        
        # Test PDF extraction
        data = test_pdf_extraction(pdf_path)
        
        # Test Odoo connection
        client = test_odoo_connection()
        
        if client and data:
            # Test lead search with extracted phone
            phone = data.get('mobile_phone', data.get('phone', ''))
            if phone:
                test_lead_search(client, phone)
        
    else:
        print("Usage: python test_file_watcher.py <path_to_pdf>")
        print("\nOr run the full service:")
        print("  python file_watcher_service.py")
        
        # Just test Odoo connection
        test_odoo_connection()

if __name__ == "__main__":
    main()