# -*- coding: utf-8 -*-
"""Đọc mail Tiến Hưng 16/09 + tải toàn bộ file đính kèm."""
import sys, os, re, json, base64, io, html as H
from pathlib import Path

SCRIPTS = r"C:\Users\admin\AppData\Local\hermes\skills\productivity\google-workspace\scripts"
sys.path.insert(0, SCRIPTS)
import google_api as ga

OUT = r"C:\Claw 2\QC\Base\mail_tienhung_1609"
os.makedirs(OUT, exist_ok=True)
MID = "1a0a9df0ffd6fd99"
svc = ga.build_service("gmail", "v1")
msg = svc.users().messages().get(userId="me", id=MID, format="full").execute()

parts = []
def walk(p, acc=""):
    mime = p.get("mimeType", "")
    body = p.get("body", {}) or {}
    parts.append({"mime": mime, "filename": p.get("filename", ""), "size": body.get("size", 0),
                  "att_id": body.get("attachmentId"), "data": body.get("data"), "acc": acc})
    for c in p.get("parts", []) or []:
        walk(c, acc + "/" + mime)
walk(msg["payload"])

print("=== CẤU TRÚC MAIL ===")
for p in parts:
    if p["mime"].startswith("multipart"): continue
    print(f'  {p["mime"]:<28} {p["size"]:>9} B | {p["filename"] or "(nội dung)"} | att={bool(p["att_id"])}')

files = []
for p in parts:
    if p["att_id"] and p["filename"]:
        a = svc.users().messages().attachments().get(userId="me", messageId=MID, id=p["att_id"]).execute()
        raw = base64.urlsafe_b64decode(a["data"])
        fn = re.sub(r'[<>:"/\\|?*]', "_", p["filename"])
        fp = os.path.join(OUT, fn)
        open(fp, "wb").write(raw)
        files.append((fp, len(raw), p["mime"]))
        print(f'  -> đã tải: {fn} ({len(raw)//1024} KB)')

for p in parts:
    if p["mime"] == "text/html" and p["data"]:
        raw = base64.urlsafe_b64decode(p["data"]).decode("utf-8", "replace")
        open(os.path.join(OUT, "noi_dung_mail.html"), "w", encoding="utf-8").write(raw)
        txt = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", raw, flags=re.S | re.I)
        txt = re.sub(r"<br\s*/?>|</p>|</div>|</tr>", "\n", txt, flags=re.I)
        txt = re.sub(r"<[^>]+>", " ", txt)
        txt = H.unescape(re.sub(r"[ \t]{2,}", " ", txt))
        txt = re.sub(r"\n\s*\n{2,}", "\n\n", txt).strip()
        open(os.path.join(OUT, "noi_dung_mail.txt"), "w", encoding="utf-8").write(txt)
        print("\n=== NỘI DUNG MAIL ===")
        print(txt[:6000])
    if p["mime"] == "text/plain" and p["data"] and not any(x[1] == "text/plain" for x in []):
        t = base64.urlsafe_b64decode(p["data"]).decode("utf-8", "replace")
        if t.strip():
            open(os.path.join(OUT, "noi_dung_mail_plain.txt"), "w", encoding="utf-8").write(t)
            print("\n=== TEXT/PLAIN ==="); print(t[:3000])
json.dump({"id": MID, "subject": msg["payload"]["headers"] and [h["value"] for h in msg["payload"]["headers"] if h["name"] == "Subject"][0],
           "files": files}, open(os.path.join(OUT, "_mail.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("\nthư mục:", OUT)
