# -*- coding: utf-8 -*-
r"""B88: tải file đính kèm của email Hằng Vật tư 'BÁO CÁO GIÁ DUNG MÔI 13.10.26' + in nội dung mail."""
import base64, os, re
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

TOKEN = r'C:\Users\admin\AppData\Local\hermes\google_token.json'
MSG = '1a1342be34d72384'
OUT = r'C:\Claw 2\Nghien cuu\Tinh-Gia-Thanh\GIA-NGUYEN-LIEU\_mail_hang_1310'
os.makedirs(OUT, exist_ok=True)

creds = Credentials.from_authorized_user_file(TOKEN)
if creds.expired and creds.refresh_token:
    from google.auth.transport.requests import Request
    creds.refresh(Request())
svc = build('gmail', 'v1', credentials=creds, cache_discovery=False)
m = svc.users().messages().get(userId='me', id=MSG, format='full').execute()
h = {x['name'].lower(): x['value'] for x in m['payload']['headers']}
print('  Tiêu đề:', h.get('subject'))
print('  Từ     :', h.get('from'))
print('  Ngày   :', h.get('date'))
print()


def walk(p, sau=''):
    ra = []
    for x in p.get('parts', []) or []:
        ra += walk(x, sau + '  ')
    fn = p.get('filename') or ''
    mt = p.get('mimeType') or ''
    bd = (p.get('body') or {}).get('data')
    if fn:
        print('  ĐÍNH KÈM: %-45s %-28s %8d B' % (fn, mt, (p.get('body') or {}).get('size') or 0))
        ra.append((fn, mt, (p.get('body') or {}).get('attachmentId')))
    elif bd and mt in ('text/plain', 'text/html'):
        txt = base64.urlsafe_b64decode(bd).decode('utf-8', 'replace')
        txt = re.sub(r'<[^>]+>', ' ', txt)
        txt = re.sub(r'&nbsp;|&amp;', ' ', txt)
        txt = re.sub(r'\s+', ' ', txt).strip()
        if len(txt) > 25:
            print('  NỘI DUNG (%s): %s' % (mt, txt[:700]))
            print()
    else:
        print('  %s- phần %s (rỗng)' % (sau, mt))
    return ra


ds = walk(m['payload'])
for fn, mt, aid in ds:
    if not aid:
        continue
    a = svc.users().messages().attachments().get(userId='me', messageId=MSG, id=aid).execute()
    raw = base64.urlsafe_b64decode(a['data'])
    p = os.path.join(OUT, fn)
    open(p, 'wb').write(raw)
    print('  -> lưu: %s (%d B)' % (p, len(raw)))
print()
print('  thư mục:', OUT)
