#!/usr/bin/env python3
"""List all customer inventory items with active IP assignments.
Uses the Gaiia public API - run with GAIIA_KEY set (source .envrc)."""

from gaiia import GaiiaClient
import json

def main():
    with GaiiaClient(timezone='America/Chicago') as g:
        # Paginate through all inventory items assigned to accounts
        all_assignments = []
        after = None
        page = 0

        while True:
            page += 1
            query = """
            query GetAssignments($after: String) {
                inventoryItems(
                    filters: {assigneeType: {equals: ACCOUNT}}
                    first: 250
                    after: $after
                ) {
                    nodes {
                        ipAddressAssignments {
                            nodes { ipAddress macAddress isActive }
                        }
                    }
                    pageInfo { hasNextPage endCursor }
                    totalCount
                }
            }
            """
            data = g.query(query, {"after": after} if after else {})
            result = data['inventoryItems']

            if page == 1:
                print(f"Total inventory items assigned to accounts: {result['totalCount']}")

            for item in result['nodes']:
                for a in item.get('ipAddressAssignments', {}).get('nodes', []):
                    if a.get('isActive') != False:  # active or None
                        all_assignments.append({
                            'macAddress': a['macAddress'],
                            'ipAddress': a['ipAddress']
                        })

            page_info = result['pageInfo']
            if not page_info.get('hasNextPage'):
                break
            after = page_info['endCursor']

        print(f"Active IP assignments found: {len(all_assignments)}")
        print()

        # Print first 20
        for a in all_assignments[:20]:
            print(f"  {a['macAddress']} -> {a['ipAddress']}")
        if len(all_assignments) > 20:
            print(f"  ... and {len(all_assignments) - 20} more")

        # Save to file
        with open('/Users/graham/dev/network/gaiia/ip_assignments.json', 'w') as f:
            json.dump(all_assignments, f, indent=2)
        print(f"\nSaved {len(all_assignments)} assignments to ip_assignments.json")

if __name__ == '__main__':
    main()
