import discord
from discord.ext import commands
import requests

# Your Discord bot token
DISCORD_BOT_TOKEN = "MTE0MTQwOTAyNjAyMjg0MjM4OA.G_p_lX.LsCjLzmStw4pmM5wZUu4VVgCajSnOpCGj4fbTQ"

# Your Telnyx API key
TELNYX_API_KEY = "KEY0194E7BF0053F90F28D1B832B029EC12_lO50YBO34Q1MhkJLFmDYWF"

# Channel ID where the bot is allowed to respond
ALLOWED_CHANNEL_ID = 1338435781274107988

# Define the bot
intents = discord.Intents.default()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)


def check_carrier_number(phone_number, api_key):
    """
    Check the carrier information of a given phone number using Telnyx API.

    Parameters:
        phone_number (str): The phone number in E.164 format (e.g., +16158304923).
        api_key (str): Your Telnyx API key.

    Returns:
        str: A formatted string with the carrier information or an error message.
    """
    url = f"https://api.telnyx.com/v2/number_lookup/{phone_number}?type=carrier"
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise an HTTPError for bad responses
        data = response.json().get("data", {})
        country = data.get("country_code", "Unknown")
        phone = data.get("phone_number", "Unknown")
        carrier = data.get("carrier", {}).get("name", "Unknown")
        return f"**Country**: {country}\n**Phone Number**: {phone}\n**Carrier**: {carrier}"
    except requests.exceptions.HTTPError as http_err:
        return f"HTTP error occurred: {http_err}"
    except Exception as err:
        return f"An error occurred: {err}"


@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")


@bot.command(name="ping")
async def ping(ctx):
    """
    A simple command to test if the bot is working.
    """
    if ctx.channel.id != ALLOWED_CHANNEL_ID:
        return  # Ignore command if it's from an unauthorized channel

    embedVar = discord.Embed(
        title="VERSCH BOT", description="", color=0x00ff00
    )
    embedVar.add_field(name="Info", value="Pong!")
    await ctx.send(embed=embedVar)


@bot.command(name="carrier")
async def carrier_lookup(ctx, phone_number: str):
    """
    Command to check the carrier of a given phone number.

    Usage: !carrier +16158304923
    """
    print(f"Carrier command received with phone number: {phone_number}")

    if ctx.channel.id != ALLOWED_CHANNEL_ID:
        print(f"Command used in unauthorized channel: {ctx.channel.id}")
        embedVar = discord.Embed(
            title="VERSCH BOT", description="Unauthorized Channel", color=0xfc0303
        )
        embedVar.add_field(
            name="Sender", value=ctx.author, inline=True
        )
        embedVar.add_field(
            name="Status", value="Unauthorized Channel", inline=True
        )
        await ctx.send(embed=embedVar)
        return

    # Check if the phone number starts with +1
    if not phone_number.startswith("+1"):
        embedVar = discord.Embed(
            title="VERSCH BOT", description="Error Occurred", color=0xfc0303
        )
        embedVar.add_field(
            name="Info", value="This bot can only be used to check United States numbers."
        )
        await ctx.send(embed=embedVar)
        return

    # Initial embed while processing
    embedVar = discord.Embed(
        title="VERSCH BOT", description="", color=0x00ff00
    )
    embedVar.add_field(
        name="Sender", value=ctx.author, inline=True
    )
    embedVar.add_field(
        name="Status", value="Checking carrier information...", inline=True
    )
    await ctx.send(embed=embedVar)

    result = check_carrier_number(phone_number, TELNYX_API_KEY)

    if "HTTP error occurred" in result or "An error occurred" in result:
        embedVar = discord.Embed(
            title="VERSCH BOT", description="Error Occurred", color=0xfc0303
        )
        embedVar.add_field(
            name="Information Retrieved", value=result, inline=False
        )
        await ctx.send(embed=embedVar)
    else:
        # Parse the result for a formatted response
        lines = result.split("\n")
        country = lines[0].replace("**Country**: ", "").strip()
        phone = lines[1].replace("**Phone Number**: ", "").strip()
        carrier = lines[2].replace("**Carrier**: ", "").strip()

        # Final embed without Sender and Status
        embedVar = discord.Embed(
            title="VERSCH BOT", description="", color=0x00ff00
        )
        embedVar.add_field(
            name="Information Retrieved",
            value=(
                f"**Country :** {country}\n"
                f"**Phone Number :** {phone}\n"
                f"**Carrier :** {carrier}"
            ),
            inline=False
        )
        await ctx.send(embed=embedVar)

# Run the bot
try:
    print("Starting the bot...")
    bot.run(DISCORD_BOT_TOKEN)
except Exception as e:
    print(f"Failed to run the bot: {e}")
