import requests
import pymysql

api_key = "2285eee4-ba07-4037-b880-165e3dda83d9"
cassanova_url = "https://api.cassanova.com"

db_config = {
    'host': 'localhost',
    'user': 'enigma_user',
    'password': 'arcana2026',
    'database': 'enigma',
    'charset': 'utf8mb4'
}

# 1. Get token
print("🔑 Richiedendo token...")
token_response = requests.post(
    f"{cassanova_url}/apikey/token",
    headers={"Content-Type": "application/json", "X-Requested-With": "*"},
    json={"apiKey": api_key},
    timeout=10
)

token = token_response.json()['access_token']
print(f"✅ Token ottenuto")

# 2. Get salespoints CON X-Version
print("📍 Richiedendo salespoint...")
sp_response = requests.get(
    f"{cassanova_url}/salespoint",
    headers={
        "Authorization": f"Bearer {token}",
        "X-Version": "1.0.0",
        "Content-Type": "application/json"
    },
    timeout=10
)

print(f"Status: {sp_response.status_code}")
print(f"Response: {sp_response.text}")

if sp_response.status_code == 200:
    data = sp_response.json()
    salespoints = data.get('salesPoint', [])  # ← CAMBIA QUI
    
    print(f"\n✅ Trovate {len(salespoints)} sedi")
    
    # 3. Insert in inv_sedi
    conn = pymysql.connect(**db_config)
    cursor = conn.cursor()
    tenant_id = 1
    
    for sp in salespoints:
        sp_id = sp.get('id')
        sp_name = sp.get('name', f'Sede {sp_id}')  # ← CAMBIA IN 'name'
        sp_city = sp.get('city', '')
        sp_address = sp.get('street', '')
        
        if sp_city:
            sp_address += f", {sp_city}"
        
        cursor.execute("""
            INSERT INTO inv_sedi (id, id_tenant, nome, indirizzo)
            VALUES (%s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
                nome = VALUES(nome),
                indirizzo = VALUES(indirizzo)
        """, (sp_id, tenant_id, sp_name, sp_address))
        
        print(f"✅ {sp_name} (ID: {sp_id})")
    
    conn.commit()
    cursor.close()
    conn.close()
    
    print(f"\n✅ Importazione completata!")
