"""Check Revit files for schedule/progress/phase data via APS API."""
import requests, json, os, time
from dotenv import load_dotenv
load_dotenv()

# Get token
resp = requests.post('https://developer.api.autodesk.com/authentication/v2/token',
    data={'grant_type':'client_credentials','scope':'data:read viewables:read'},
    auth=(os.getenv('APS_CLIENT_ID'), os.getenv('APS_CLIENT_SECRET')))
token = resp.json()['access_token']

# Load all URNs from config
with open('viewer_config.json') as f:
    config = json.load(f)

for model in config['models']:
    urn = model['urn']
    name = model['name']
    print(f'\n{"="*60}')
    print(f'MODEL: {name}')
    print(f'{"="*60}')

    # Get metadata
    meta = requests.get(
        f'https://developer.api.autodesk.com/modelderivative/v2/designdata/{urn}/metadata',
        headers={'Authorization': f'Bearer {token}'}
    ).json()

    views = meta.get('data', {}).get('metadata', [])
    if not views:
        print('  No views found')
        continue

    for v in views:
        print(f"  View: {v['name']} | role={v['role']}")

    guid_3d = [v for v in views if v['role'] == '3d']
    if not guid_3d:
        guid_3d = views
    guid = guid_3d[0]['guid']

    # Get properties with retry
    for attempt in range(3):
        props_resp = requests.get(
            f'https://developer.api.autodesk.com/modelderivative/v2/designdata/{urn}/metadata/{guid}/properties',
            headers={'Authorization': f'Bearer {token}'},
            params={'forceget': 'true'}
        )
        props = props_resp.json()
        collection = props.get('data', {}).get('collection', [])
        if collection:
            break
        print(f'  Attempt {attempt+1}: empty collection, waiting...')
        time.sleep(5)

    print(f'  Total elements: {len(collection)}')
    if not collection:
        continue

    # Collect all categories and search
    keywords = ['phase', 'schedule', 'time', 'date', 'start', 'end', 'duration',
                'progress', 'plan', 'baseline', 'task', 'phasing', 'period',
                'created', 'demolished', 'construction', 'sequence']

    all_categories = set()
    found_props = []

    for elem in collection:
        for cat_name, cat_props in elem.get('properties', {}).items():
            all_categories.add(cat_name)
            if isinstance(cat_props, dict):
                for prop_name, prop_val in cat_props.items():
                    search_text = (cat_name + ' ' + prop_name + ' ' + str(prop_val)).lower()
                    if any(kw in search_text for kw in keywords):
                        found_props.append((cat_name, prop_name, prop_val, elem.get('name', '')))

    print(f'\n  All categories: {sorted(all_categories)}')
    print(f'\n  Schedule/Phase related: {len(found_props)} properties found')
    seen = set()
    for cat, pname, val, elem_name in found_props[:30]:
        key = f'{cat}|{pname}|{val}'
        if key not in seen:
            seen.add(key)
            print(f'    [{cat}] {pname} = {val}  (ex: {elem_name})')

    # Only check first model to save time
    break
