import win32com.client as win32
import os
import sys
import time

sys.stdout.reconfigure(encoding='utf-8')

def main():
    doc_path = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\Bao cao lam mau\Bao cao\Bao_cao_tien_do_lam_mau_tuan_26_29.docx"
    xls_path = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\Bao cao lam mau\da lam sach\Tuan_29_13.07-19.07_DA-LAM-SACH.xlsx"
    
    # Try opening Outlook if not already running
    print("Launching Outlook...")
    os.system('start outlook')
    time.sleep(3) # Wait for Outlook to initialize
    
    try:
        outlook = win32.Dispatch('outlook.application')
        mail = outlook.CreateItem(0)
        mail.Subject = "Báo cáo tiến độ làm mẫu tuần 26 - 29"
        
        body = (
            "Kính gửi anh/chị,\n\n"
            "Tôi xin gửi báo cáo tiến độ làm mẫu tuần 26 - 29 cùng tệp tin dữ liệu làm sạch tuần 29 đính kèm bên dưới:\n\n"
            "- Báo cáo tiến độ làm mẫu (.docx)\n"
            "- File dữ liệu làm sạch (.xlsx)\n\n"
            "Trân trọng,\n"
        )
        mail.Body = body
        
        if os.path.exists(doc_path):
            mail.Attachments.Add(doc_path)
            print("Attached:", doc_path)
        else:
            print("Error: Document not found at", doc_path)
            
        if os.path.exists(xls_path):
            mail.Attachments.Add(xls_path)
            print("Attached:", xls_path)
        else:
            print("Error: Excel file not found at", xls_path)
            
        mail.Display()
        print("Outlook email draft opened successfully.")
        return
        
    except Exception as e:
        print("Error dispatching Outlook, trying alternative methods:", e)
        
    # If Outlook dispatch completely fails, open the directory in explorer to let the user drag & drop
    try:
        print("Opening file explorer for manual attachment...")
        # Open explorer select on the word document
        if os.path.exists(doc_path):
            os.system(f'explorer /select,"{doc_path}"')
    except Exception as e:
        print("Error opening explorer:", e)

if __name__ == "__main__":
    main()
