import json,os,re
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
docmap=json.load(open("/tmp/trello_docs.json"))  # fileId -> [card names]
t=json.load(open(os.path.expanduser("~/.config/cinik-gdoc/token.json")))
c=Credentials(token=t["token"],refresh_token=t["refresh_token"],token_uri=t["token_uri"],client_id=t["client_id"],client_secret=t["client_secret"],scopes=t["scopes"]);c.refresh(Request())
drive=build("drive","v3",credentials=c,cache_discovery=False)
shared_ok=already=share_fail=0
empty=[]; inaccessible=[]; okcount=0
ids=list(docmap.keys())
for i,fid in enumerate(ids):
    # 1) partage anyone=writer (idempotent)
    try:
        perms=drive.permissions().list(fileId=fid,fields="permissions(type,role)",supportsAllDrives=True).execute().get("permissions",[])
        has=any(p.get("type")=="anyone" and p.get("role")=="writer" for p in perms)
        if has: already+=1
        else:
            drive.permissions().create(fileId=fid,body={"type":"anyone","role":"writer"},fields="id",supportsAllDrives=True).execute()
            shared_ok+=1
    except HttpError as e:
        share_fail+=1; inaccessible.append((fid,str(e)[:60])); 
        continue
    # 2) audit vide
    try:
        n=len(drive.files().export(fileId=fid,mimeType="text/plain").execute().decode("utf-8","replace").strip())
        if n<400: empty.append((fid,n,docmap[fid][0][:40]))
        else: okcount+=1
    except Exception as e:
        pass
    if (i+1)%150==0: print(f"...{i+1}/{len(ids)}",flush=True)
print("=== RESULTAT PASSE UNIVERSELLE ===")
print(f"total docs board: {len(ids)}")
print(f"partage: deja_ok={already} nouvellement_partagés={shared_ok} echec_partage(non possédés/inaccessibles)={share_fail}")
print(f"contenu: OK={okcount} VIDES={len(empty)}")
print("--- VIDES (max 60) ---")
for fid,n,nm in empty[:60]: print(f"  {fid} chars={n} [{nm}]")
json.dump({"empty":empty,"inaccessible_n":share_fail,"shared_ok":shared_ok,"already":already},open("/tmp/universal_result.json","w"))
