"""
Detailed vTiger field inspection for SalesOrder
"""
import asyncio
import sys
import json
sys.path.insert(0, '/app')

from app.services.vtiger_service import get_vtiger_service

async def inspect_fields():
    vtiger = get_vtiger_service()
    
    print("="*60)
    print("Inspecting SalesOrder for Arbodania (3x760)")
    print("="*60)
    
    query = "SELECT * FROM SalesOrder WHERE account_id='3x760';"
    results = await vtiger.query(query)
    
    if results:
        print(f"\n✅ Found {len(results)} sales orders\n")
        for i, order in enumerate(results, 1):
            print(f"\n{'='*60}")
            print(f"Sales Order #{i}")
            print(f"{'='*60}")
            for key, value in sorted(order.items()):
                if value and str(value).strip():  # Only show non-empty values
                    print(f"{key:30s} = {value}")
    
    print("\n" + "="*60)
    print("Inspecting ALL SalesOrders (first 5)")
    print("="*60)
    
    query2 = "SELECT * FROM SalesOrder LIMIT 5;"
    all_orders = await vtiger.query(query2)
    
    if all_orders:
        print(f"\n✅ Found {len(all_orders)} sales orders total\n")
        
        # Collect all unique field names
        all_fields = set()
        for order in all_orders:
            all_fields.update(order.keys())
        
        print(f"Total unique fields: {len(all_fields)}")
        print("\nField names related to frequency/recurring:")
        freq_fields = [f for f in sorted(all_fields) if any(x in f.lower() for x in ['freq', 'recur', 'billing', 'period', 'subscr'])]
        if freq_fields:
            for f in freq_fields:
                print(f"  - {f}")
        else:
            print("  ⚠️ No frequency-related fields found")
        
        print("\nAll field names:")
        for f in sorted(all_fields):
            print(f"  - {f}")

if __name__ == "__main__":
    asyncio.run(inspect_fields())
