import os
import calendar
from datetime import datetime
from dotenv import load_dotenv
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    ApplicationBuilder, CommandHandler, CallbackQueryHandler, ContextTypes
)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

load_dotenv(override=True)
TOKEN = os.getenv("TELEGRAM_TOKEN")
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")
CHANNEL_ID = os.getenv("TELEGRAM_CHAT_ID")

driver = None
wait = None

def selenium_login_and_goto_report():
    global driver, wait
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    driver = webdriver.Chrome(options=options)
    wait = WebDriverWait(driver, 30)
    driver.get("https://ssodeme.com/admin/login")
    user_input = wait.until(EC.presence_of_element_located((By.NAME, "username")))
    pass_input = wait.until(EC.presence_of_element_located((By.NAME, "password")))
    user_input.clear()
    user_input.send_keys(USERNAME)
    pass_input.clear()
    pass_input.send_keys(PASSWORD)
    submit_btn = driver.find_element(By.CSS_SELECTOR, "input[type='submit']")
    submit_btn.click()
    wait.until(EC.url_contains('/admin'))
    driver.get("https://ssodeme.com/admin/reports")
    wait.until(EC.presence_of_element_located((By.NAME, "filter_start_date")))

def build_calendar(year, month):
    cal = calendar.monthcalendar(year, month)
    keyboard = []
    for week in cal:
        row = []
        for day in week:
            if day == 0:
                row.append(InlineKeyboardButton(" ", callback_data="ignore"))
            else:
                day_str = str(day)
                cb_data = f"gun_{year}-{str(month).zfill(2)}-{day_str.zfill(2)}"
                row.append(InlineKeyboardButton(day_str, callback_data=cb_data))
        keyboard.append(row)
    nav_row = [InlineKeyboardButton("⬅️ Önceki Ay", callback_data=f"prev_{year}_{month}")]
    keyboard.append(nav_row)
    return InlineKeyboardMarkup(keyboard)

def get_report_for_day(selected_day):
    global driver, wait
    # Düzgün tarih formatı: "YYYY-MM-DD HH:MM" (örn 2025-11-05 00:00)
    start = f"{selected_day} 00:00"
    end = f"{selected_day} 23:59"
    start_input = wait.until(EC.presence_of_element_located((By.NAME, "filter_start_date")))
    end_input = driver.find_element(By.NAME, "filter_end_date")
    start_input.clear()
    start_input.send_keys(start)
    end_input.clear()
    end_input.send_keys(end)
    getir_btn = driver.find_element(By.ID, "reportFilter")
    getir_btn.click()
    table = wait.until(EC.presence_of_element_located((By.ID, "example2")))
    tbody = table.find_element(By.TAG_NAME, "tbody")
    wait.until(lambda d: len(tbody.find_elements(By.TAG_NAME, "tr")) > 0)
    rows = tbody.find_elements(By.TAG_NAME, "tr")

    # TABLOYU KONSOLA YAZDIR
    print("\n--- TABLO SATIRLARI ---")
    for i, row in enumerate(rows):
        cols = row.find_elements(By.TAG_NAME, "td")
        col_texts = [col.text.replace('\n', ' ').strip() for col in cols]
        print(f"Satır {i}: {col_texts}")
    print("--- TABLO BİTTİ ---\n")

    betmoon_row = None
    rapor_baslangic = f"{selected_day} 00:00:00"
    rapor_bitis = f"{selected_day} 23:59:59"
    # Tarih bilgisini son satırda çek
    if rows:
        last_cols = rows[-1].find_elements(By.TAG_NAME, "td")
        if last_cols and len(last_cols) == 1 and "arasını göstermektedir" in last_cols[0].text:
            import re
            metin = last_cols[0].text
            m = re.search(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ile (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})', metin)
            if m:
                rapor_baslangic = m.group(1)
                rapor_bitis = m.group(2)
    # BetMoon satırını esnek bulmak için:
    for row in rows:
        cols = row.find_elements(By.TAG_NAME, "td")
        if cols and "betmoon" in cols[0].text.strip().lower():
            betmoon_row = [col.text.replace('\n', ' ').strip() for col in cols]
            break
    return betmoon_row, rapor_baslangic, rapor_bitis

def generate_message(row, baslangic, bitis):
    if not row:
        return "🔔 BetMoonV3 için tablo sonucu bulunamadı."
    return (
        "📊 Betmoon - Detaylı Kasa Raporu\n"
        f"Başlangıç: {baslangic}\n"
        f"Bitiş: {bitis}\n\n"
        "═══════════════════════════\n\n"
        "📈 TÜM İŞLEM DETAYLARI\n"
        f"✅ Başarılı Yatırım Adeti: {row[3]}\n"
        f"✅ Başarılı Yatırım: {row[2]}\n"
        f"✅ Başarılı Çekim Adeti: {row[6]}\n"
        f"✅ Başarılı Çekim: {row[5]}\n"
    )

async def mutabakat(update: Update, context: ContextTypes.DEFAULT_TYPE):
    selenium_login_and_goto_report()
    now = datetime.now()
    header = f"{now.strftime('%B %Y')} için gün seçin:"
    keyboard = build_calendar(now.year, now.month)
    await update.message.reply_text(header, reply_markup=keyboard)

async def handle_calendar(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    data = query.data

    if data.startswith("gun_"):
        tarih = data[4:]    # YYYY-MM-DD
        await query.answer()
        await query.edit_message_text(
            f"Seçilen gün: {tarih}\n"
            "Mutabakat raporunuz hazırlanıyor...\n"
            "Bu işlem 1-3 dakika sürebilir. Lütfen bekleyiniz."
        )
        row, rapor_baslangic, rapor_bitis = get_report_for_day(tarih)
        mesaj = generate_message(row, rapor_baslangic, rapor_bitis)
        await context.bot.send_message(chat_id=CHANNEL_ID, text=mesaj)
        # Driver session kapat (isteğe bağlı)
        global driver
        if driver:
            driver.quit()
            driver = None

    elif data.startswith("prev_"):
        _, y, m = data.split("_")
        y, m = int(y), int(m) - 1
        if m < 1:
            m = 12
            y -= 1
        header = f"{calendar.month_name[m]} {y} için gün seçin:"
        keyboard = build_calendar(y, m)
        await query.answer()
        await query.edit_message_text(header, reply_markup=keyboard)
    elif data == "ignore":
        await query.answer()

if __name__ == "__main__":
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler("mutabakat", mutabakat))
    app.add_handler(CallbackQueryHandler(handle_calendar, pattern="^(gun_|prev_|ignore)"))
    print("Bot aktif! /mutabakat ile takvim menüsünü deneyin.")
    app.run_polling()