"""Search ALL e-conomic invoices for Hosting - AR2"""
import asyncio
import sys
import os
import aiohttp

# Add app to path
sys.path.insert(0, '/Users/christianthomas/DEV/bmc_hub_dev')

from app.core.config import settings


async def main():
    headers = {
        "X-AppSecretToken": settings.ECONOMIC_APP_SECRET_TOKEN,
        "X-AgreementGrantToken": settings.ECONOMIC_AGREEMENT_GRANT_TOKEN,
        "Content-Type": "application/json"
    }
    
    endpoints = [
        "https://restapi.e-conomic.com/invoices/drafts",
        "https://restapi.e-conomic.com/invoices/sent",
        "https://restapi.e-conomic.com/invoices/booked",
        "https://restapi.e-conomic.com/invoices/paid",
        "https://restapi.e-conomic.com/invoices/unpaid"
    ]
    
    customers_with_ar2 = set()
    
    async with aiohttp.ClientSession() as session:
        for endpoint in endpoints:
            print(f"\nChecking {endpoint.split('/')[-1]}...")
            
            try:
                async with session.get(endpoint, headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        invoices = data.get('collection', [])
                        print(f"  Found {len(invoices)} invoices")
                        
                        for inv in invoices:
                            # Fetch full invoice with lines
                            self_link = inv.get('self')
                            if not self_link:
                                continue
                                
                            async with session.get(self_link, headers=headers) as inv_resp:
                                if inv_resp.status == 200:
                                    full_inv = await inv_resp.json()
                                    lines = full_inv.get('lines', [])
                                    
                                    for line in lines:
                                        product_name = line.get('product', {}).get('name') or line.get('description', '')
                                        
                                        if 'AR2' in product_name.upper() or 'HOSTING' in product_name.upper() or 'ABONNEMENT' in product_name.upper() or 'PERIODE' in product_name.upper():
                                            customer_num = full_inv.get('customer', {}).get('customerNumber')
                                            inv_num = full_inv.get('bookedInvoiceNumber') or full_inv.get('draftInvoiceNumber')
                                            inv_date = full_inv.get('date')
                                            period = line.get('period', {})
                                            
                                            customers_with_ar2.add(customer_num)
                                            print(f"    ✅ Customer {customer_num} | Invoice {inv_num} | {inv_date} | {product_name[:60]}")
                                            if period:
                                                print(f"       Period: {period}")
                                            
            except Exception as e:
                print(f"  ❌ Error: {e}")
    
    print(f"\n{'='*60}")
    print(f"📊 SUMMARY: Found {len(customers_with_ar2)} customers with Hosting - AR2")
    print(f"   Customer numbers: {sorted(customers_with_ar2)}")
    print('='*60)


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