from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import base64, json, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

token_path = os.path.expanduser('~/AppData/Local/hermes/google_token.json')
with open(token_path) as f:
    token_data = json.load(f)
creds = Credentials.from_authorized_user_info(token_data)
service = build('gmail', 'v1', credentials=creds)

msg = MIMEMultipart()
msg['To'] = 'ngoducminh84@gmail.com'
msg['From'] = 'ngoducminh84@gmail.com'
msg['Subject'] = '📋 Báo cáo tổng hợp đánh giá quy trình BTChem (V2.0)'

body = """
Kính gửi anh Minh,

Em gửi anh báo cáo tổng hợp đánh giá quy trình làm việc BTChem, phiên bản V2.0 đã được cập nhật và hoàn thiện.

Nội dung báo cáo:
- Khảo sát 309 câu hỏi từ 10 phòng ban
- 14 phân hệ Microsoft Dynamics 365 Business Central
- Đánh giá từ 3 chuyên gia: ERP, Kế toán & Tài chính, Sản xuất
- Điểm nghẽn, rủi ro chiến lược và lộ trình điều chỉnh

File đính kèm gồm 2 định dạng:
1. Báo cáo chính (.md)
2. Báo cáo (.docx)

Anh xem và cho ý kiến nhé.

Trân trọng,
Trợ lý AI
"""

msg.attach(MIMEText(body, 'plain', 'utf-8'))

# Đính kèm file MD
md_path = r"C:\antigra-DS\CLAW_LAM_VIEC\ERP\CAUHOIKHAOSATMS\Tong hop - Offical\Bao_cao_Tong_hop_Quy_trinh_BTChem.md"
with open(md_path, 'rb') as f:
    att = MIMEBase('application', 'octet-stream')
    att.set_payload(f.read())
    encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment', filename='Bao_cao_Tong_hop_Quy_trinh_BTChem.md')
    msg.attach(att)

# Đính kèm file DOCX
docx_path = r"C:\antigra-DS\CLAW_LAM_VIEC\ERP\CAUHOIKHAOSATMS\Tong hop - Offical\Bao_cao_Tong_hop_Quy_trinh_BTChem_V2.docx"
with open(docx_path, 'rb') as f:
    att = MIMEBase('application', 'vnd.openxmlformats-officedocument.wordprocessingml.document')
    att.set_payload(f.read())
    encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment', filename='Bao_cao_Tong_hop_Quy_trinh_BTChem_V2.docx')
    msg.attach(att)

raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
result = service.users().messages().send(userId='me', body={'raw': raw}).execute()
print(f"✅ Đã gửi email! Message ID: {result['id']}")
