﻿import os, json
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
OPS=r"C:\Users\daito\company\ops"
SID="13jmH9LBj4LFa6lbET-DyopA9oCt77RxnXS-_PXWhHSY"
c=Credentials.from_authorized_user_file(os.path.join(OPS,"token_sheets.json"),["https://www.googleapis.com/auth/spreadsheets"])
if c.expired and c.refresh_token: c.refresh(Request())
s=build("sheets","v4",credentials=c,cache_discovery=False)
os.makedirs("source",exist_ok=True)
tabs=["１５号アタックリスト","台東区 広告営業ターゲット2025.3.25","まとめ","請求書管理","請求書設定","担当者マスター"]
res=s.spreadsheets().values().batchGet(spreadsheetId=SID,ranges=[f"'{t}'!A1:Z1005" for t in tabs]).execute()
for t,vr in zip(tabs,res.get("valueRanges",[])):
    vals=vr.get("values",[])
    # trim trailing empty rows
    vals=[r for r in vals if any((x or "").strip() for x in r)]
    json.dump(vals,open(f"source/{t}.json","w",encoding="utf-8"),ensure_ascii=False)
    print(f"{t}: {len(vals)} non-empty rows; header={vals[0][:8] if vals else '[]'}")
