# Crypto Price Plugin
# CMD: .price usdt ton bnb

import aiohttp
from asyncio import sleep

from . import get_string, LOGS, ultroid_cmd


COINS = {
    "usdt": "tether",
    "ton": "the-open-network",
    "bnb": "binancecoin",
    "btc": "bitcoin",
    "eth": "ethereum",
    "sol": "solana",
}


async def fetch_prices(ids):
    ids_str = ",".join(ids)
    url = (
        "https://api.coingecko.com/api/v3/simple/price"
        f"?ids={ids_str}&vs_currencies=usd,inr"
    )

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.json()


@ultroid_cmd(pattern="price( (.*)|$)")
async def crypto_price(e):
    args = e.pattern_match.group(2)

    if not args:
        return await e.eor("Usage: `.price usdt ton bnb`")

    coins = args.lower().split()
    valid = [c for c in coins if c in COINS]

    if not valid:
        return await e.eor("Unsupported coin.")

    msg = await e.eor("Fetching prices...")

    try:
        ids = [COINS[c] for c in valid]
        data = await fetch_prices(ids)

        lines = []
        for coin in valid:
            cid = COINS[coin]
            usd = data[cid]["usd"]
            inr = data[cid]["inr"]
            lines.append(f"{coin.upper()}: ${usd} | ₹{inr}")

        await msg.edit("\n".join(lines))

    except Exception as ex:
        LOGS.exception(ex)
        await msg.edit(f"Error: {ex}")

    await sleep(1)
