import os
import logging
import gspread
from google.oauth2.service_account import Credentials
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes, CommandHandler, ConversationHandler

# === НАСТРОЙКИ ===
TOKEN = "7825570683:AAGqJkCCKZVNmSt2kbgJj5M6Oh8nkvOHgvE"
SHEET_URL = "https://docs.google.com/spreadsheets/d/1PZNpn9zYbUrGSvTT8AcsUJkUhOPKmw9EZxi2kh9x7Kg/edit#gid=0"
SERVICE_KEY_PATH = "/home/ultraee/priks.ee/botapp/abiding-splicer-398114-3b84d3e78408.json"

# === GOOGLE SHEETS ===
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = Credentials.from_service_account_file(SERVICE_KEY_PATH, scopes=scope)
client = gspread.authorize(creds)
sheet = client.open_by_url(SHEET_URL).sheet1

# === ЛОГИ ===
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# === ЭТАПЫ ДИАЛОГА ===
WHAT, PLACE, NOTE = range(3)

# === СТАРТ ===
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [["🔍 Поиск", "➕ Добавить товар"]]
    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
    await update.message.reply_text("Привет! Выберите действие:", reply_markup=reply_markup)

# === ПОИСК ===
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = update.message.text.lower()
    if text == "🔍 поиск":
        await update.message.reply_text("Напиши ключевое слово для поиска товара:")
        return
    elif text == "➕ добавить товар":
        await update.message.reply_text("Что за товар? 📦")
        return WHAT

    rows = sheet.get_all_records()
    results = [
        f"📦 {row['Что']}\n📍 {row['Место']}\n📝 {row['Описание']}"
        for row in rows if text in row['Что'].lower()
    ]
    if results:
        await update.message.reply_text("\n\n".join(results))
    else:
        await update.message.reply_text("❌ Ничего не найдено.")

# === ДОБАВЛЕНИЕ ТОВАРА ===
async def add_what(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['what'] = update.message.text
    await update.message.reply_text("На какой полке он лежит? 📍")
    return PLACE

async def add_place(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['place'] = update.message.text
    await update.message.reply_text("Добавь описание или комментарий 📝")
    return NOTE

async def add_note(update: Update, context: ContextTypes.DEFAULT_TYPE):
    what = context.user_data['what']
    place = context.user_data['place']
    note = update.message.text
    sheet.append_row([what, place, note])
    await update.message.reply_text("✅ Товар добавлен!")
    return ConversationHandler.END

async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("❌ Отменено.")
    return ConversationHandler.END

# === ЗАПУСК ===
def main():
    app = ApplicationBuilder().token(TOKEN).build()

    conv_handler = ConversationHandler(
        entry_points=[MessageHandler(filters.Regex("^➕ Добавить товар$"), add_what)],
        states={
            WHAT: [MessageHandler(filters.TEXT & ~filters.COMMAND, add_what)],
            PLACE: [MessageHandler(filters.TEXT & ~filters.COMMAND, add_place)],
            NOTE: [MessageHandler(filters.TEXT & ~filters.COMMAND, add_note)],
        },
        fallbacks=[CommandHandler("cancel", cancel)]
    )

    app.add_handler(CommandHandler("start", start))
    app.add_handler(conv_handler)
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

    app.run_polling()

if __name__ == "__main__":
    main()
