import subprocess, json

# Get token
result = subprocess.run(['curl', '-s', '-X', 'POST', 'http://192.168.1.127:8091/api/user/token-auth/',
    '-H', 'Content-Type: application/json',
    '-d', '{"email":"kmorhaim@hotmail.com","password":"nYKG9!x?s8?hCyeb"}'],
    capture_output=True, text=True)
token = json.loads(result.stdout)['access_token']

TABLE_ID = 715
headers = {'Authorization': f'JWT {token}', 'Content-Type': 'application/json'}

# Fields to create
fields = [
    ('Date du chantier', 'date'),
    ('Lieu', 'text'),
    ('Météo', 'text'),
    ('Équipe', 'text'),
    ('Transcription', 'long_text'),
    ('Observations', 'long_text'),
    ('Anomalies', 'long_text'),
    ('Statut', 'single_select'),
    ('Statut_valeurs', 'text'),  # placeholder
    ('PDF_URL', 'url'),
    ('Photos', 'long_text'),
    ('Créé le', 'created_time'),
    ('Modifié le', 'last_modified_time'),
]

# Single select settings
ss_choices = json.dumps([
    {'name': 'Draft'},
    {'name': 'Validé'},
    {'name': 'Envoyé'},
    {'name': 'Archivé'},
])

for name, ftype in fields:
    if ftype == 'single_select':
        body = json.dumps({
            'type': 'single_select',
            'name': name,
            'settings': {'choices': json.loads(ss_choices)}
        })
    elif ftype == 'text' and name in ('Statut_valeurs',):
        continue  # skip placeholder
    else:
        body = json.dumps({'type': ftype, 'name': name})

    result = subprocess.run([
        'curl', '-s', '-X', 'POST',
        f'http://192.168.1.127:8091/api/database/fields/table/{TABLE_ID}/',
        '-H', f'Authorization: JWT {token}',
        '-H', 'Content-Type: application/json',
        '-d', body
    ], capture_output=True, text=True)
    
    resp = json.loads(result.stdout)
    if 'id' in resp:
        print(f'✓ {resp["name"]} ({resp["id"]})')
    else:
        print(f'✗ {resp.get("detail", resp)}')

# List all fields
result = subprocess.run([
    'curl', '-s',
    f'http://192.168.1.127:8091/api/database/fields/table/{TABLE_ID}/',
    '-H', f'Authorization: JWT {token}'
], capture_output=True, text=True)
fields = json.loads(result.stdout)
print("\n--- Table fields ---")
for f in fields:
    print(f"  {f['id']:4d} | {f['name']:<20s} | {f['type']}")
