#!/usr/bin/env python3
"""
Teste verschiedene Query-Parameter um additionalColumns aus API zu bekommen
"""

import requests
import subprocess
from datetime import datetime

BASE_URL = "https://crm.bitbylaw.com"
API_KEY = "e53def10eea27b92a6cd00f40a3e09a4"
HEADERS = {
    "X-Api-Key": API_KEY,
    "Content-Type": "application/json"
}

doc_id = None
collection_id = None
test_sync_id = f"SYNC-{datetime.now().strftime('%Y%m%d-%H%M%S')}"

try:
    # Setup
    print("Setup...")
    doc = requests.post(f"{BASE_URL}/api/v1/CDokumente", headers=HEADERS, json={"name": "Test Doc"}).json()
    doc_id = doc['id']
    
    collection = requests.post(f"{BASE_URL}/api/v1/CAICollections", headers=HEADERS, json={"name": "Test Col"}).json()
    collection_id = collection['id']
    
    # Link und setze syncId in DB
    requests.post(f"{BASE_URL}/api/v1/CDokumente/{doc_id}/cAICollections", headers=HEADERS, json={"id": collection_id})
    subprocess.run([
        "docker", "exec", "espocrm-db", "mariadb",
        "-u", "espocrm", "-pdatabase_password", "espocrm",
        "-e", f"UPDATE c_a_i_collection_c_dokumente SET sync_id='{test_sync_id}' WHERE c_dokumente_id='{doc_id}';"
    ], capture_output=True)
    
    print(f"Doc: {doc_id}, Col: {collection_id}, syncId: {test_sync_id}\n")
    
    # Teste verschiedene Query-Parameter
    params_to_test = [
        {},
        {"select": "id,name,syncId"},
        {"select": "id,name,sync_id"},
        {"additionalColumns": "true"},
        {"columns": "true"},
        {"includeColumns": "true"},
        {"expand": "columns"},
        {"maxSize": 10, "select": "syncId"},
        {"loadAdditionalFields": "true"},
    ]
    
    print("="*80)
    print("Teste Query-Parameter:")
    print("="*80 + "\n")
    
    for i, params in enumerate(params_to_test, 1):
        param_str = ", ".join([f"{k}={v}" for k, v in params.items()]) if params else "keine"
        print(f"{i}. Parameter: {param_str}")
        
        response = requests.get(
            f"{BASE_URL}/api/v1/CDokumente/{doc_id}/cAICollections",
            headers=HEADERS,
            params=params
        )
        
        if response.status_code == 200:
            data = response.json()
            if 'list' in data and len(data['list']) > 0:
                first = data['list'][0]
                if 'syncId' in first or 'sync_id' in first:
                    print(f"   ✅ additionalColumn gefunden!")
                    print(f"      syncId: {first.get('syncId', first.get('sync_id'))}")
                else:
                    print(f"   ❌ Keine additionalColumn (Felder: {len(first)})")
            else:
                print(f"   ⚠️  Leere Liste")
        else:
            print(f"   ❌ Status: {response.status_code}")
        print()

finally:
    print("Cleanup...")
    if doc_id:
        requests.delete(f"{BASE_URL}/api/v1/CDokumente/{doc_id}", headers=HEADERS)
    if collection_id:
        requests.delete(f"{BASE_URL}/api/v1/CAICollections/{collection_id}", headers=HEADERS)

print("="*80)
