import requests
import sqlite3
import time
import json

def send_telegram_message(token, chat_id, message):
    url = f"https://api.telegram.org/bot{token}/sendMessage"
    payload = {'chat_id': chat_id, 'text': message}
    try:
        response = requests.post(url, data=payload)
        if response.status_code == 200:
            print("Message sent successfully.")
        else:
            print(f"Failed to send message: {response.content}")
    except requests.RequestException as e:
        print(f"An error occurred: {e}")

def fetch_data():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.3'
    }

    try:
        response = requests.get(
            'https://mihanblockchain.com/wp-admin/admin-ajax.php?action=ajax_get_best_exchanges_orders&nonce=c4b6c02c5a&coin=usdt',
            headers=headers)
        response.raise_for_status()
        return json.loads(response.text)
    except requests.RequestException as e:
        print(f"Network error: {e}")
        return None
    except json.JSONDecodeError:
        print("Failed to parse JSON")
        return None

def store_data(data, cursor, conn):
    try:
        # First, insert the new data
        for exchange in data['Exchanges']:
            buy_price = int(float(exchange['best_asks_price']))
            sell_price = int(float(exchange['best_bids_price']))
            exchange_name = exchange['title']
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
            cursor.execute("INSERT INTO exchange_data VALUES (?, ?, ?, ?)",
                           (timestamp, exchange_name, buy_price, sell_price))

        # Fetch the latest record for each exchange and find the highest sell and lowest buy
        cursor.execute("SELECT DISTINCT exchange_name FROM exchange_data")
        exchange_names = cursor.fetchall()

        max_sell = -1
        min_buy = float('inf')
        max_sell_exchange = ""
        min_buy_exchange = ""

        for exchange_name_tuple in exchange_names:
            exchange_name = exchange_name_tuple[0]
            cursor.execute("SELECT sell_price, buy_price FROM exchange_data WHERE exchange_name=? ORDER BY timestamp DESC LIMIT 1",
                           (exchange_name,))
            sell_price, buy_price = cursor.fetchone()
            if sell_price > max_sell:
                max_sell = sell_price
                max_sell_exchange = exchange_name
            if buy_price < min_buy:
                min_buy = buy_price
                min_buy_exchange = exchange_name

        price_difference = max_sell - min_buy

        message = f"Max Sell Price: {max_sell} at {max_sell_exchange}\n" \
                  f"Min Buy Price: {min_buy} at {min_buy_exchange}\n" \
                  f"Price Difference: {price_difference}"

        bot_token = "5865501194:AAFJ3n3eJmDwgo_bqEkqfsP19s-O2pGwF2Q"
        group_chat_id = -1001796474067  # Replace with your actual chat ID (usually a negative number)
        send_telegram_message(bot_token, group_chat_id, message)

        conn.commit()

    except sqlite3.Error as e:
        print(f"Database error: {e}")


def main():
    conn = sqlite3.connect('exchange_data.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS exchange_data
                (timestamp TEXT, exchange_name TEXT, buy_price INTEGER, sell_price INTEGER)''')
    conn.commit()

    while True:
        data = fetch_data()
        if data:
            store_data(data, c, conn)
        time.sleep(10)

    conn.close()

if __name__ == "__main__":
    main()
