import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)
r = client.post('/api/auth/login', json={'username': 'admin', 'password': 'admin123'})
token = r.json()['access_token']
h = {'Authorization': f'Bearer {token}'}

batches = client.get('/api/production/batches', headers=h).json()
passports_resp = client.get('/api/passports', headers=h)
used = {p['batch_id'] for p in passports_resp.json()} if passports_resp.status_code == 200 else set()
free = [b for b in batches if b['id'] not in used][:1]

if not free:
    print('No free batches')
    sys.exit()

b = free[0]
print(f"Creating passport for batch {b['batch_number']}...")
r2 = client.post('/api/passports', json={'batch_id': b['id']}, headers=h)
print(f"Status: {r2.status_code}")
if r2.status_code != 201:
    print(r2.text[:1000])
else:
    data = r2.json()
    print(f"Created: passport_id={data['passport_id']}")
