import imaplib
import email
from email.header import decode_header
import requests
import json
import os
import re
from openpyxl import load_workbook

# ==========================================================
# 1. 설정 정보 (접속 정보 및 경로)
# ==========================================================
EMAIL_USER = "buddhakim71@gmail.com"  # 본인 메일
EMAIL_PASS = "zhxn tdnv uzzy asrv"     # 앱 비밀번호
API_KEY = "AIzaSyAjE9dMwwdBRkz4quEQAWQch8FQichJELA"
MODEL_NAME = "models/gemini-2.5-flash-lite"

TEMPLATE_PATH = r"E:\파이썬프로그램\인보이스\template.xlsx"
RESULT_PATH = r"E:\파이썬프로그램\인보이스\final_completed_invoice.xlsx"

def get_latest_order_email():
    try:
        print("1. Gmail 서버 연결 중...")
        mail = imaplib.IMAP4_SSL("imap.gmail.com")
        mail.login(EMAIL_USER, EMAIL_PASS)
        mail.select("INBOX")

        status, messages = mail.search(None, 'ALL')
        if not messages[0]: return None

        email_ids = messages[0].split()
        for e_id in reversed(email_ids):
            _, data = mail.fetch(e_id, "(RFC822)")
            msg = email.message_from_bytes(data[0][1])

            subject, encoding = decode_header(msg.get("Subject"))[0]
            if isinstance(subject, bytes):
                subject = subject.decode(encoding if encoding else "utf-8", errors="ignore")

            if "주문" in subject:
                print(f"✅ 처리할 메일 발견: {subject}")
                if msg.is_multipart():
                    for part in msg.walk():
                        if part.get_content_type() == "text/plain":
                            return part.get_payload(decode=True).decode("utf-8", errors="ignore")
                else:
                    return msg.get_payload(decode=True).decode("utf-8", errors="ignore")
        return None
    except Exception as e:
        print(f"❌ 메일 읽기 오류: {e}")
        return None

def process_with_gemini(content):
    print("2. AI(Gemini) 분석 요청 중...")
    url = f"https://generativelanguage.googleapis.com/v1beta/{MODEL_NAME}:generateContent?key={API_KEY}"
    prompt = (
        f"추출:상호명,품목명,수량,단가. 결과는 반드시 JSON 배열로만 응답해.\n"
        f"형식: [{{'customer': '상호', 'item': '품목', 'qty': '수량', 'price': '단가'}}]\n"
        f"본문: {content}"
    )
    try:
        response = requests.post(url, json={"contents": [{"parts": [{"text": prompt}]}]})
        return response.json()['candidates'][0]['content']['parts'][0]['text']
    except Exception as e:
        print(f"❌ AI 오류: {e}")
        return None

def save_to_template_excel(ai_text):
    print("3. 양식에 데이터 입력 중...")
    try:
        # JSON 데이터만 쏙 뽑아내는 정교한 필터링
        match = re.search(r'\[.*\]', ai_text, re.DOTALL)
        if match:
            clean_json = match.group().replace("'", "\"")
            items = json.loads(clean_json)
        else:
            print("❌ AI 응답에서 데이터를 찾을 수 없습니다.")
            return

        if not os.path.exists(TEMPLATE_PATH):
            print(f"❌ 오류: {TEMPLATE_PATH} 파일이 없습니다!")
            return

        wb = load_workbook(TEMPLATE_PATH)
        ws = wb.active

        # 시작 행 번호 (양식에 맞게 수정)
        start_row = 10 

        for idx, i in enumerate(items):
            def clean_num(val):
                if not val: return 0
                num_str = re.sub(r'[^0-9]', '', str(val))
                return int(num_str) if num_str else 0

            current_row = start_row + idx
            
            # 엑셀 칸 주소 지정 (B:상호, C:품목, D:수량, E:단가)
            ws[f"B{current_row}"] = i.get('customer', '상호미상')
            ws[f"C{current_row}"] = i.get('item', '품목미상')
            ws[f"D{current_row}"] = clean_num(i.get('qty'))
            ws[f"E{current_row}"] = clean_num(i.get('price'))
            ws[f"F{current_row}"] = f"=D{current_row}*E{current_row}"

        wb.save(RESULT_PATH)
        print(f"🎉 모든 작업 성공! 파일 확인: {RESULT_PATH}")
    except Exception as e:
        print(f"❌ 엑셀 저장 오류: {e}")

if __name__ == "__main__":
    content = get_latest_order_email()
    if content:
        ai_res = process_with_gemini(content)
        if ai_res:
            save_to_template_excel(ai_res)
    else:
        print("❌ 처리할 새 주문 메일이 없습니다.")