import imaplib
import email
from email.header import decode_header
from bs4 import BeautifulSoup
import re
import requests

# === НАСТРОЙКИ ===
USERNAME = "почта_gmail@gmail.com"
APP_PASSWORD = "PASSWORD"  # не обычный пароль!
SEARCH_PHRASE = "ЛУКОЙЛ-УРАЛНЕФТЕПРОДУКТ"

# Telegram
TELEGRAM_BOT_TOKEN = "токен"
TELEGRAM_CHAT_ID = "идентификатор чата"  # может быть отрицательным для группы

# === ФУНКЦИЯ ОТПРАВКИ В TELEGRAM ===
def send_to_telegram(text):
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    payload = {
        "chat_id": TELEGRAM_CHAT_ID,
        "text": text,
        "parse_mode": "HTML"
    }
    try:
        response = requests.post(url, data=payload)
        if not response.ok:
            print(f"Ошибка Telegram: {response.text}")
    except Exception as e:
        print(f"Не удалось отправить в Telegram: {e}")

# === ПОДКЛЮЧЕНИЕ ===
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(USERNAME, APP_PASSWORD)
mail.select("inbox")

# Проверим, существует ли папка "Лукойл", иначе создадим
folder_name = "LUKOIL"
try:
    mail.create(folder_name)
    print(f"Создана папка: {folder_name}")
except:
    pass  # папка уже существует или доступ запрещён — не критично

# Получаем последние 50 писем
status, messages = mail.search(None, "ALL")
email_ids = messages[0].split()[-50:]

processed_count = 0
for email_id in reversed(email_ids):
    status, msg_data = mail.fetch(email_id, "(RFC822)")
    raw_email = msg_data[0][1]
    msg = email.message_from_bytes(raw_email)

    # Декодируем тему
    subject_raw = msg["Subject"]
    subject_decoded = ""
    if subject_raw:
        decoded_fragments = decode_header(subject_raw)
        for fragment, encoding in decoded_fragments:
            if isinstance(fragment, bytes):
                encoding = encoding or "utf-8"
                try:
                    fragment = fragment.decode(encoding)
                except (UnicodeDecodeError, LookupError):
                    fragment = fragment.decode("utf-8", errors="replace")
            subject_decoded += fragment

    if SEARCH_PHRASE.lower() not in subject_decoded.lower():
        continue

    # Извлекаем HTML-тело
    body = ""
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == "text/html":
                payload = part.get_payload(decode=True)
                charset = part.get_content_charset() or "utf-8"
                try:
                    body = payload.decode(charset)
                except (UnicodeDecodeError, LookupError):
                    body = payload.decode("utf-8", errors="replace")
                break
    else:
        if msg.get_content_type() == "text/html":
            payload = msg.get_payload(decode=True)
            charset = msg.get_content_charset() or "utf-8"
            try:
                body = payload.decode(charset)
            except (UnicodeDecodeError, LookupError):
                body = payload.decode("utf-8", errors="replace")

    if not body:
        continue

    # === ПАРСИНГ ===
    soup = BeautifulSoup(body, "html.parser")
    date_elem = soup.find("td", string="Дата выдачи ФД")
    date_str = date_elem.find_next("td").get_text(strip=True) if date_elem else "Неизвестно"

    check_items = soup.find_all("table", class_="check_item")
    result = None
    for item in check_items:
        rows = item.find_all("tr")
        if len(rows) < 2:
            continue
        first_text = rows[0].get_text()
        if "бензин" in first_text.lower():
            fuel_match = re.search(r"(?:Бензин\s+автомобильный|Автомобильный\s+бензин|Бензин)\s+(.*?),\s*л", first_text, re.IGNORECASE)
            fuel_name = fuel_match.group(1).strip() if fuel_match else "Неизвестно"

            qty_price_cell = rows[1].find("td")
            total_cell = rows[1].find_all("td")[-1]

            if qty_price_cell and total_cell:
                qty_price_text = qty_price_cell.get_text(strip=True)
                total = total_cell.get_text(strip=True)

                if " x " in qty_price_text:
                    parts = qty_price_text.split(" x ")
                    qty = parts[0].strip()
                    price = parts[1].strip()
                else:
                    qty, price = "??", "??"
                result = f"{date_str}: Бензин {fuel_name} {qty} литров x {price} рублей = {total} рублей"
                break

    if result:
        print(result)
        send_to_telegram(result)
        processed_count += 1

        # Перемещаем письмо в папку "Лукойл"
        try:
            mail.copy(email_id, folder_name)
            mail.store(email_id, '+FLAGS', '\\Deleted')  # помечаем на удаление из INBOX
        except Exception as e:
            print(f"Не удалось переместить письмо {email_id}: {e}")

# Окончательно удаляем помеченные письма из INBOX
mail.expunge()

mail.close()
mail.logout()

if processed_count == 0:
    print(f"Чеков от {SEARCH_PHRASE} с бензином не найдено.")
else:
    print(f"Обработано и перемещено {processed_count} чеков.")
