import requests, json

BASE = 'http://localhost:8090'

# Login
r = requests.post(f'{BASE}/api/collections/_superusers/auth-with-password', json={
    'identity': 'rune@famx.dk',
    'password': 'Rune27!!'
})
token = r.json().get('token', '')
headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}

# Check if sessions collection already exists
r = requests.get(f'{BASE}/api/collections', headers=headers)
existing = [c.get('name') for c in r.json().get('items', [])]
print(f"Existing collections: {existing}")

if 'sessions' in existing:
    print("sessions collection already exists")
else:
    # Create sessions collection
    schema = [
        {"name": "group_id", "type": "text", "required": True, "unique": True},
        {"name": "parent_id", "type": "text", "required": False},
        {"name": "project_id", "type": "text", "required": False},
        {"name": "task_id", "type": "text", "required": False},
        {"name": "widget_ids", "type": "json", "required": False},
        {"name": "state", "type": "select", "required": True,
         "options": {"values": ["active", "parked", "closed"]}},
    ]
    r = requests.post(f'{BASE}/api/collections', headers=headers, json={
        'name': 'sessions',
        'type': 'base',
        'schema': schema,
        'listRule': None,
        'viewRule': None,
        'createRule': None,
        'updateRule': None,
        'deleteRule': None,
    })
    print(f"Create sessions: {r.status_code} - {r.text[:200]}")

# Verify
r = requests.get(f'{BASE}/api/collections/sessions', headers=headers)
print(f"Verify: {r.status_code} - {json.dumps(r.json(), indent=2)[:300]}")