import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters
from google import genai
import PIL.Image
import pandas as pd
import json
import io
import os
from datetime import datetime

# [설정] 본인의 정보를 입력하세요
GEMINI_API_KEY = "여기에_구글_API_키를_입력하세요"
TELEGRAM_BOT_TOKEN = "여기에_텔레그램_토큰을_입력하세요"
EXCEL_FILE = r"E:\영업비용_집계.xlsx" # 저장될 경로

client = genai.Client(api_key=GEMINI_API_KEY)

async def process_receipt(update: Update, context: ContextTypes.DEFAULT_TYPE):
    try:
        user_name = update.message.from_user.full_name # 보낸 사람 이름
        photo_info = update.message.photo[-1]
        file_uid = photo_info.file_unique_id # 사진 고유번호
        
        # 1. 중복 사진 체크 (AI 호출 전 차단하여 비용 절감)
        if os.path.exists(EXCEL_FILE):
            df_temp = pd.read_excel(EXCEL_FILE)
            if 'file_uid' in df_temp.columns and file_uid in df_temp['file_uid'].values:
                await update.message.reply_text("⚠️ 이미 등록된 영수증입니다.")
                return

        # 2. 이미지 다운로드 및 AI 분석
        photo = await photo_info.get_file()
        photo_bytes = await photo.download_as_bytearray()
        img = PIL.Image.open(io.BytesIO(photo_bytes))
        
        await update.message.reply_text(f"[{user_name}]님, 품목별 상세 분석 중...")

        prompt = "영수증 분석 후 상호명, 날짜, 총액, 품목리스트(이름, 가격)를 JSON으로 응답해줘."
        response = client.models.generate_content(model="gemini-2.0-flash-lite", contents=[prompt, img])
        data = json.loads(response.text.replace('```json', '').replace('```', '').strip())

        # 3. 1품목 1행 방식으로 데이터 정리
        rows = []
        for item in data['items']:
            rows.append({
                'recorded_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'sender': user_name,
                'date': data['date'],
                'store': data['store'],
                'item_name': item.get('name'),
                'item_price': item.get('price'),
                'total_receipt_amount': data['total_amount'],
                'file_uid': file_uid
            })

        # 4. 엑셀 저장
        df_new = pd.DataFrame(rows)
        if os.path.exists(EXCEL_FILE):
            df_old = pd.read_excel(EXCEL_FILE)
            df_final = pd.concat([df_old, df_new], ignore_index=True)
        else:
            df_final = df_new
        
        df_final.to_excel(EXCEL_FILE, index=False)
        await update.message.reply_text(f"✅ {data['store']} 기록 완료!")

    except Exception as e:
        await update.message.reply_text(f"❌ 오류: {e}")

if __name__ == '__main__':
    application = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()
    application.add_handler(MessageHandler(filters.PHOTO, process_receipt))
    application.run_polling()