"""
Diagnostico: baja el Excel de Arequipa de SharePoint y muestra que hojas
y que tablas nombradas detecta openpyxl, y cuantas filas tiene cada una.
Asi sabemos por que el sync cae al fallback (10000 filas).
"""
import os, io, openpyxl, requests, msal

CLIENT_ID     = os.environ["MS_CLIENT_ID"]
TENANT_ID     = os.environ["MS_TENANT_ID"]
REFRESH_TOKEN = os.environ["MS_REFRESH_TOKEN"]
SHAREPOINT_SITE = "escuelarefrigeracion.sharepoint.com"
SITE_PATH       = "/sites/ASESORASCOMERCIALES"
SUBFOLDER       = "2. BASE PROSPECTOS/BASE GENERAL"
SCOPES          = ["Sites.Read.All", "Files.Read.All"]

ARCHIVOS = ["Base Sede Arequipa.xlsx", "Base Diana Chavez.xlsx"]  # uno malo + uno bueno para comparar

app = msal.PublicClientApplication(CLIENT_ID, authority=f"https://login.microsoftonline.com/{TENANT_ID}")
tok = app.acquire_token_by_refresh_token(REFRESH_TOKEN, scopes=SCOPES)["access_token"]
h = {"Authorization": f"Bearer {tok}"}

sid = requests.get(f"https://graph.microsoft.com/v1.0/sites/{SHAREPOINT_SITE}:{SITE_PATH}", headers=h).json()["id"]
drives = requests.get(f"https://graph.microsoft.com/v1.0/sites/{sid}/drives", headers=h).json()["value"]
did = next((d["id"] for d in drives if "document" in d["name"].lower() or "compartid" in d["name"].lower()), drives[0]["id"])
items = requests.get(f"https://graph.microsoft.com/v1.0/drives/{did}/root:/{SUBFOLDER}:/children", headers=h).json()["value"]

for nombre in ARCHIVOS:
    it = next((x for x in items if x["name"] == nombre), None)
    print("\n" + "="*60)
    if not it:
        print(f"❌ NO ENCONTRADO en SharePoint: '{nombre}'")
        print("   Archivos disponibles:", [x["name"] for x in items if x["name"].endswith(".xlsx")])
        continue
    print(f"📄 {nombre}")
    cont = requests.get(f"https://graph.microsoft.com/v1.0/drives/{did}/items/{it['id']}/content", headers=h).content
    wb = openpyxl.load_workbook(io.BytesIO(cont), data_only=True)
    for ws in wb.worksheets:
        print(f"  Hoja: '{ws.title}'  dims={ws.dimensions}  max_row={ws.max_row}")
        tbls = list(ws.tables.keys())
        print(f"    Tablas nombradas: {tbls}")
        for tn, tb in ws.tables.items():
            print(f"      · {tn} -> ref={tb.ref}")
