#!/usr/bin/env python3
"""
Debug script to analyze PDF form fields and their values
This will help identify missing field mappings
"""

import sys
from pathlib import Path
import PyMuPDF as fitz
from PyPDF2 import PdfReader

def analyze_pdf_fields(pdf_path: str):
    """Analyze all form fields in a PDF"""
    print(f"\n=== ANALYZING PDF: {pdf_path} ===")
    
    # Method 1: PyMuPDF
    print("\n--- PyMuPDF Fields ---")
    try:
        doc = fitz.open(pdf_path)
        for page_num in range(doc.page_count):
            page = doc[page_num]
            widgets = page.widgets()
            
            if widgets:
                print(f"\nPage {page_num + 1} ({len(widgets)} fields):")
                for widget in widgets:
                    field_name = widget.field_name
                    field_value = widget.field_value
                    field_type = widget.field_type_string
                    print(f"  '{field_name}' = '{field_value}' (Type: {field_type})")
            else:
                print(f"Page {page_num + 1}: No form fields")
        doc.close()
    except Exception as e:
        print(f"PyMuPDF error: {e}")
    
    # Method 2: PyPDF2
    print("\n--- PyPDF2 Fields ---")
    try:
        with open(pdf_path, 'rb') as file:
            reader = PdfReader(file)
            
            if reader.is_encrypted:
                print("PDF is encrypted, attempting to decrypt...")
                reader.decrypt('')
            
            if '/AcroForm' in reader.trailer['/Root']:
                form = reader.trailer['/Root']['/AcroForm']
                if '/Fields' in form:
                    fields = form['/Fields']
                    print(f"Found {len(fields)} form fields:")
                    
                    for field in fields:
                        field_obj = field.get_object()
                        field_name = field_obj.get('/T', 'Unknown')
                        field_value = field_obj.get('/V', '')
                        field_type = field_obj.get('/FT', 'Unknown')
                        
                        # Clean up field name and value
                        if hasattr(field_name, 'decode'):
                            field_name = field_name.decode('utf-8', errors='ignore')
                        if hasattr(field_value, 'decode'):
                            field_value = field_value.decode('utf-8', errors='ignore')
                        
                        print(f"  '{field_name}' = '{field_value}' (Type: {field_type})")
                else:
                    print("No /Fields found in AcroForm")
            else:
                print("No AcroForm found in PDF")
                
    except Exception as e:
        print(f"PyPDF2 error: {e}")

def main():
    if len(sys.argv) != 2:
        print("Usage: python debug_pdf_fields.py <pdf_file>")
        print("\nExample:")
        print('python debug_pdf_fields.py "D:\\Customer Docs\\2025\\08 - August\\Bradley Hauck\\Bradley Hauck Credit App.pdf"')
        return
    
    pdf_path = sys.argv[1]
    if not Path(pdf_path).exists():
        print(f"Error: File not found: {pdf_path}")
        return
    
    analyze_pdf_fields(pdf_path)

if __name__ == "__main__":
    main()