import json,os,re,urllib.request
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
def fc(o,a):
    if isinstance(o,dict):
        for k,v in o.items():
            if k=="TRELLO_API_KEY":a["k"]=v
            if k=="TRELLO_TOKEN":a["t"]=v
            fc(v,a)
    elif isinstance(o,list):
        for x in o:fc(x,a)
a={};fc(json.load(open(os.path.expanduser("~/.claude.json"))),a);KEY,TOK=a["k"],a["t"]
cards=json.load(urllib.request.urlopen(f"https://api.trello.com/1/boards/639c89fef17d6801ff768752/cards?fields=name,desc&limit=1000&key={KEY}&token={TOK}",timeout=90))
docre=re.compile(r"docs\.google\.com/document/d/([A-Za-z0-9_-]+)")
m={}
for c in cards:
    for fid in set(docre.findall(c.get("desc","") or "")): m.setdefault(fid,c["name"][:42])
t=json.load(open(os.path.expanduser("~/.config/cinik-gdoc/token.json")))
cr=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"]);cr.refresh(Request())
drive=build("drive","v3",credentials=cr,cache_discovery=False)
empty=[];unshared=[];okc=0;inacc=0
for fid,nm in m.items():
    try:
        n=len(drive.files().export(fileId=fid,mimeType="text/plain").execute().decode("utf-8","replace").strip())
        perms=drive.permissions().list(fileId=fid,fields="permissions(type,role)").execute().get("permissions",[])
        sh=any(p.get("type")=="anyone" and p.get("role")=="writer" for p in perms)
        if n<400: empty.append((nm,n))
        else: okc+=1
        if not sh: unshared.append(nm)
    except Exception: inacc+=1
print("docs board (frais):",len(m),"| OK:",okc,"| inaccessibles:",inacc)
print("VIDES:",len(empty))
for nm,n in empty: print(f"   vide[{n}] {nm}")
print("NON PARTAGÉS:",len(unshared))
for nm in unshared[:40]: print(f"   nonpartage {nm}")
json.dump({"empty":empty,"unshared":unshared},open("/tmp/verify_result.json","w"))
print("DONE")
