from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import asyncio
import time
import requests
from datetime import datetime
from pathlib import Path

# === Basit TXT log ayarı ===
LOG_FILE = "commands.log"

def is_group(update: Update) -> bool:
    chat = update.effective_chat
    return bool(chat and chat.type in ("group", "supergroup"))

def log_command(update: Update, command_name: str, handled: bool):
    user = update.effective_user
    chat = update.effective_chat
    msg  = update.effective_message

    ts = datetime.now().isoformat(timespec="seconds")
    line = (
        f"{ts} | handled={int(handled)} | "
        f"chat_type={getattr(chat, 'type', '')} | chat_id={getattr(chat, 'id', '')} | "
        f"user_id={getattr(user, 'id', '')} | username={getattr(user, 'username', '')} | "
        f"name={(getattr(user, 'first_name', '') or '')} {(getattr(user, 'last_name', '') or '')} | "
        f"command={command_name} | text={(getattr(msg, 'text', '') or '').strip()}\n"
    )
    Path(LOG_FILE).parent.mkdir(parents=True, exist_ok=True)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(line)


def log_site(command_name, durum, saniye):
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            print(
                f"{datetime.now().isoformat(timespec='seconds')} | SITE | "
                f"command={command_name} | sonuc={durum} | sure={saniye:.1f}s",
                file=f,
            )
    except Exception:
        pass

# === Komutlar ===
async def saatlik_deposit(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    # Sadece gruplarda çalıştır
    if not is_group(update):
        log_command(update, "rapor", handled=False)
        return

    log_command(update, "rapor", handled=True)
    await update.message.reply_text(f'Raporunuzu hazırlıyorum, lütfen bekleyin {update.effective_user.first_name} Bey')
    url = "https://telegram.grandoperabonus.com/anasayfa/saatlik_deposit"
    _t0 = time.monotonic()
    try:
        _r = await asyncio.to_thread(requests.get, url, timeout=120)
        log_site("saatlik_deposit", "HTTP " + str(_r.status_code), time.monotonic() - _t0)
    except Exception as _e:
        log_site("saatlik_deposit", type(_e).__name__, time.monotonic() - _t0)
        raise

async def gunsonu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if not is_group(update):
        log_command(update, "gunsonu", handled=False)
        return

    log_command(update, "gunsonu", handled=True)
    await update.message.reply_text(f'Raporunuzu hazırlıyorum, lütfen bekleyin {update.effective_user.first_name} Bey')
    url = "https://telegram.grandoperabonus.com/anasayfa/gunluksorgu"
    _t0 = time.monotonic()
    try:
        _r = await asyncio.to_thread(requests.get, url, timeout=120)
        log_site("gunsonu", "HTTP " + str(_r.status_code), time.monotonic() - _t0)
    except Exception as _e:
        log_site("gunsonu", type(_e).__name__, time.monotonic() - _t0)
        raise

async def tc(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if not is_group(update):
        log_command(update, "tc", handled=False)
        return

    # Buraya gelindiyse grup: logla ve devam et
    log_command(update, "tc", handled=True)

    try:
        username = context.args[0]
        await update.message.reply_text(f'Kullanıcı için TC Kimlik bilgileri sorgulanıyor.. 🔍 {username}')
        url = "https://telegram.grandoperabonus.com/anasayfa/tcsorgu?username=" + username
        _t0 = time.monotonic()
        try:
            _r = await asyncio.to_thread(requests.get, url, timeout=120)
            log_site("tc", "HTTP " + str(_r.status_code), time.monotonic() - _t0)
        except Exception as _e:
            log_site("tc", type(_e).__name__, time.monotonic() - _t0)
            raise
    except (IndexError, ValueError):
        await update.effective_message.reply_text("Kullanım: /tc <kullanıcı adı>")


async def ozet(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if not is_group(update):
        log_command(update, "ozet", handled=False)
        return

    # Buraya gelindiyse grup: logla ve devam et
    log_command(update, "ozet", handled=True)

    try:
        username = context.args[0]
        await update.message.reply_text(f'Kullanıcı için bilgiler sorgulanıyor.. 🔍 {username}')
        url = "https://telegram.grandoperabonus.com/anasayfa/uye_ozet?username=" + username
        _t0 = time.monotonic()
        try:
            _r = await asyncio.to_thread(requests.get, url, timeout=120)
            log_site("ozet", "HTTP " + str(_r.status_code), time.monotonic() - _t0)
        except Exception as _e:
            log_site("ozet", type(_e).__name__, time.monotonic() - _t0)
            raise
    except (IndexError, ValueError):
        await update.effective_message.reply_text("Kullanım: /ozet <kullanıcı adı>")

# === Bot setup ===
app = ApplicationBuilder().token("7465549518:AAHX_RE3CKymysFL-1tPG87MsMLtMIGq7P4").build()

app.add_handler(CommandHandler("rapor", saatlik_deposit))
app.add_handler(CommandHandler("gunsonu", gunsonu))
# /tc artik @grandtc_bot (klasor: Python Telegram - Grand TC) uzerinde calisiyor. Eski satir: app.add_handler(CommandHandler("tc", tc))
app.add_handler(CommandHandler("ozet", ozet))
app.run_polling()
