import os
import json
import random
import string
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

# ======================
# НАСТРОЙКИ
# ======================
BOT_TOKEN = '8150780351:AAG-_zes7sQ1JDuJMzvBeSbDdvXtkgXKzHA'
ADMIN_ID = 6045832073  # Замени на свой Telegram ID

ALLOWED_FILE = "allowed.json"
DOMAIN_FILE = "domain.txt"
HASHES_FILE = "hashes.json"

# ======================
# УТИЛИТЫ
# ======================

def load_json_file(filepath, default):
    if os.path.exists(filepath):
        try:
            with open(filepath, "r") as f:
                return json.load(f)
        except Exception:
            print(f"⚠️ Файл повреждён: {filepath}")
    return default

def save_json_file(filepath, data):
    with open(filepath, "w") as f:
        json.dump(data, f)

def load_allowed():
    return load_json_file(ALLOWED_FILE, [])

def save_allowed(allowed):
    save_json_file(ALLOWED_FILE, allowed)

def get_domain():
    if os.path.exists(DOMAIN_FILE):
        with open(DOMAIN_FILE, "r") as f:
            return f.read().strip()
    return "http://localhost"

def set_domain(domain):
    with open(DOMAIN_FILE, "w") as f:
        f.write(domain.strip())

def load_hashes():
    return load_json_file(HASHES_FILE, {})

def save_hashes(hashes):
    save_json_file(HASHES_FILE, hashes)

def generate_hash(length=64):
    return ''.join(random.choices(string.hexdigits.lower(), k=length))

# ======================
# КОМАНДЫ
# ======================

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    allowed = load_allowed()
    if user_id not in allowed:
        return
    await update.message.reply_text(
    "/create – создание ссылки\n"
    "/createapprove – создание ссылки с необходимостью подтверждения транзакции"
    )

async def add(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != ADMIN_ID:
        return

    if len(context.args) != 1 or not context.args[0].isdigit():
        await update.message.reply_text("Использование: /add [id]")
        return

    user_id = int(context.args[0])
    allowed = load_allowed()
    if user_id not in allowed:
        allowed.append(user_id)
        save_allowed(allowed)
        await update.message.reply_text(f"✅ Доступ выдан пользователю {user_id}")
    else:
        await update.message.reply_text("⚠️ Пользователь уже в списке")

async def domain(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != ADMIN_ID:
        return

    if len(context.args) != 1:
        await update.message.reply_text("Использование: /domain [url]")
        return

    set_domain(context.args[0])
    await update.message.reply_text(f"🌐 Домен обновлён: {context.args[0]}")

async def create_link(update: Update, context: ContextTypes.DEFAULT_TYPE, link_type: str):
    user_id = update.effective_user.id
    allowed = load_allowed()
    if user_id not in allowed:
        return

    domain = get_domain()
    hash_value = generate_hash()

    # Запоминаем тип ссылки
    hashes = load_hashes()
    hashes[hash_value] = link_type
    save_hashes(hashes)

    full_link = f"{domain}/transaction/{hash_value}"
    await update.message.reply_text(f"🔗 Ваша ссылка: {full_link}")

async def create(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await create_link(update, context, "create")

async def createapprove(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await create_link(update, context, "createapprove")

# ======================
# ЗАПУСК БОТА
# ======================

if __name__ == "__main__":
    app = ApplicationBuilder().token(BOT_TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("add", add))
    app.add_handler(CommandHandler("domain", domain))
    app.add_handler(CommandHandler("create", create))
    app.add_handler(CommandHandler("createapprove", createapprove))

    print("✅ Бот запущен...")
    app.run_polling()