import requests
import json
import time
import random
import string
import re

# ================= CONFIG =================
BOT_TOKEN = "8640856567:AAFWbmCwLuW39fQP0G-YaKDy6q6TV9QXxg0"  
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/"
EXTERNAL_API_URL = "http://number-free1year.vercel.app/?apikey=toxicadminn&number="   # 👈 API डालना मत भूलना

ADMIN_ID = 8777992150  

offset = 0
last_update_id = None   # ✅ duplicate fix

# ===== DATABASE =====
users = {}
redeem_codes = {}
admin_mode = set()
waiting_for_code = set()
waiting_for_generate = set()   # ✅ NEW

# =========================================

def get_updates(offset):
    url = API_URL + "getUpdates"
    params = {"timeout": 100, "offset": offset}
    return requests.get(url, params=params).json()

def send_message(chat_id, text, reply_markup=None):
    url = API_URL + "sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "HTML"
    }

    if reply_markup:
        payload["reply_markup"] = json.dumps(reply_markup)

    requests.post(url, data=payload)

def get_keyboard():
    return {
        "keyboard": [
            [{"text": "📱 Phone Lookup"}],
            [{"text": "💳 Check Credits"}, {"text": "🎟 Redeem Code"}],
            [{"text": "💰 Buy Credits"}]
        ],
        "resize_keyboard": True
    }

def is_valid_number(text):
    return text.isdigit() and len(text) == 10

def call_external_api(phone):
    try:
        response = requests.get(EXTERNAL_API_URL + phone)
        return response.json()
    except:
        return {"error": "API failed or invalid response"}

# ===== CREDIT SYSTEM =====

def get_user_credit(chat_id):
    if chat_id not in users:
        users[chat_id] = 3
    return users[chat_id]

def use_credit(chat_id):
    users[chat_id] -= 1

def generate_code(credits):
    code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    redeem_codes[code] = credits
    return code

def redeem_code(chat_id, code):
    if code in redeem_codes:
        users[chat_id] += redeem_codes[code]
        del redeem_codes[code]
        return True
    return False

# ================= UI =================

def welcome_text():
    return (
        "🔥 <b>WELCOME TO PHONE INTEL BOT</b> 🔥\n\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "📡 <b>Fast • Accurate • Clean Data</b>\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n\n"
        "📱 Click below to start lookup\n\n"
        "👑 <b>OWNER:</b> JET X FLY 🕊️ (@kingxsellerg1 )"
    )

def ask_number_text():
    return (
        "📞 <b>ENTER MOBILE NUMBER</b>\n\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "🔢 Send <b>10-digit number</b>\n"
        "⚠️ No spaces / no +91\n"
        "━━━━━━━━━━━━━━━━━━━━━━"
    )

def loading_text():
    return (
        "⏳ <b>Processing Request...</b>\n"
        "━━━━━━━━━━━━━━━━━━━━━━"
    )

def format_result(data):
    return (
        "📊 <b>LOOKUP RESULT</b>\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        f"<pre>{json.dumps(data, indent=4)}</pre>\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "👑 <b>OWNER:</b> JET X FLY 🕊️ (@kingxsellerg1 )"
    )

def error_text():
    return (
        "❌ <b>INVALID INPUT</b>\n\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "📵 Please send a valid 10-digit number\n"
        "━━━━━━━━━━━━━━━━━━━━━━"
    )

def no_credit_text():
    return (
        "🚫 <b>NO CREDITS LEFT</b>\n\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "💰 Click on Buy Credits\n"
        "👑 <b>OWNER:</b> JET X FLY 🕊️ (@kingxsellerg1 )"
    )

def credit_text(chat_id):
    return f"💳 <b>Your Credits:</b> {users[chat_id]}"

def buy_text():
    return (
        "💰 <b>BUY CREDITS</b>\n\n"
        "━━━━━━━━━━━━━━━━━━━━━━\n"
        "📩 Contact Admin\n"
        "👑 <b>JET X FLY 🕊️ (@kingxsellerg1 )</b>\n"
        "━━━━━━━━━━━━━━━━━━━━━━"
    )

# ================= MAIN LOOP =================

print("Bot running (fixed + stable)...")

while True:
    try:
        updates = get_updates(offset)

        if "result" not in updates:
            continue

        for update in updates["result"]:

            if update["update_id"] == last_update_id:
                continue

            last_update_id = update["update_id"]
            offset = update["update_id"] + 1

            if "message" not in update:
                continue

            msg = update["message"]
            chat_id = msg["chat"]["id"]

            if "text" not in msg:
                continue

            text = msg["text"].strip()

            get_user_credit(chat_id)

            # ===== ADMIN =====
            if text == "/admin" and chat_id == ADMIN_ID:
                admin_mode.add(chat_id)
                send_message(chat_id,
                    "👑 ADMIN PANEL\n\n"
                    "dashboard\nusers\ngenerate\nexit"
                )
                continue

            if text == "/exit" and chat_id == ADMIN_ID:
                admin_mode.discard(chat_id)
                send_message(chat_id, "❌ Admin mode OFF")
                continue

            if chat_id in admin_mode:

                if text.lower() == "dashboard":
                    send_message(chat_id,
                        f"📊 DASHBOARD\n\n"
                        f"👥 Users: {len(users)}\n"
                        f"🎟 Codes: {len(redeem_codes)}"
                    )
                    continue

                elif text.lower() == "users":
                    send_message(chat_id, f"👥 Total Users: {len(users)}")
                    continue

                elif text.lower() == "generate":
                    waiting_for_generate.add(chat_id)
                    send_message(chat_id, "Kitne credits ka code banana hai?\nExample: 10")
                    continue

                elif chat_id in waiting_for_generate:
                    if text.isdigit():
                        credits = int(text)
                        code = generate_code(credits)
                        send_message(chat_id, f"✅ Code: <code>{code}</code>\nCredits: {credits}")
                    else:
                        send_message(chat_id, "❌ Sirf number bhejo")

                    waiting_for_generate.remove(chat_id)
                    continue

                elif text.lower() == "exit":
                    admin_mode.discard(chat_id)
                    send_message(chat_id, "❌ Admin mode OFF")
                    continue

            # START
            if text == "/start":
                send_message(chat_id, welcome_text(), get_keyboard())

            elif text == "💳 Check Credits":
                send_message(chat_id, credit_text(chat_id))

            elif text == "💰 Buy Credits":
                send_message(chat_id, buy_text())

            elif text == "🎟 Redeem Code":
                waiting_for_code.add(chat_id)
                send_message(chat_id, "🔑 Send your code")

            elif chat_id in waiting_for_code:
                if redeem_code(chat_id, text):
                    send_message(chat_id, f"✅ Credits Added\n💳 Total: {users[chat_id]}")
                else:
                    send_message(chat_id, "❌ Invalid Code")
                waiting_for_code.remove(chat_id)

            elif text == "📱 Phone Lookup":
                send_message(chat_id, ask_number_text())

            elif is_valid_number(text):
                if get_user_credit(chat_id) <= 0:
                    send_message(chat_id, no_credit_text())
                    continue

                use_credit(chat_id)
                send_message(chat_id, loading_text())

                data = call_external_api(text)
                send_message(chat_id, format_result(data))
                send_message(chat_id, f"💳 Credits Left: {users[chat_id]}")

            else:
                send_message(chat_id, error_text())

        time.sleep(1)

    except Exception as e:
        print("Error:", e)
        time.sleep(3)
        
        
        
        

#nano script.sh


#while true; do
 #  python bot9.py
   #echo "Restarting bot..."
 #  sleep 5
#done


#chmod +x script.sh

#nohup bash script.sh > log.txt 2>&1 &

#check karne ke liye  aux | grep script.sh

#band karne ke liye  pkill -f script.sh