import requests
import re
from . import ultroid_cmd, eor

@ultroid_cmd(pattern="bid(?: |$)(.*)")
async def fetch_fragment(e):
    username = e.pattern_match.group(1).strip() or "scum"
    url = f"https://fragment.com/username/{username}"

    headers = {
        "Host": "fragment.com",
        "Connection": "keep-alive",
        "sec-ch-ua": '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "X-Aj-Referer": f"https://fragment.com/?query={username}",
        "X-Requested-With": "XMLHttpRequest",
        "sec-ch-ua-mobile": "?1",
        "User-Agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36",
        "sec-ch-ua-platform": '"Android"',
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": f"https://fragment.com/?query={username}",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cookie": "stel_ssid=14da3a56490ba14022_1489304648777473836; stel_dt=-330"
    }

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        response_text = response.text

        # Initial extraction attempts
        name_match = re.search(r'"t":"([^"]*Fragment)"', response_text)
        name_part = name_match.group(1) if name_match else None

        bid_match = re.search(r'div class=\\"tm-section-box tm-section-bid-info\\">.*?Minimum Bid \*.*?icon-before icon-ton\\">(\d+)<', response_text, re.DOTALL)
        if bid_match:
            min_bid = bid_match.group(1)
        else:
            fallback_bid_match = re.search(r'btn btn-primary js-place-bid-btn\\"data-bid-amount=\\"(\d+)\\"', response_text, re.DOTALL)
            min_bid = fallback_bid_match.group(1) if fallback_bid_match else None

        auction_match = re.search(r'class=\\"reel\\"><b class=\\"digit timer-s0\\" data-val=\\"(\d+)\\".*?data-val=\\"(\d+)\\"', response_text, re.DOTALL)
        if auction_match:
            hours = auction_match.group(1)
            minutes = auction_match.group(2)
            auction_time = f"{hours} hours and {minutes} minutes"
        else:
            auction_time = None

        # If nothing found in initial tags
        if not name_part and not min_bid and not auction_time:
            sold_match = re.search(r'class=\\"domain\\">.t.me<\\/span><\\/span><\\/span>.*?class=\\"tm-section-header-status tm-status-unavail\\">Sold<', response_text, re.DOTALL)
            if sold_match:
                sale_price_match = re.search(r'Sale Price<\\/th>.*?icon-before icon-ton\\">([\d,]+)<', response_text, re.DOTALL)
                sale_price = sale_price_match.group(1) if sale_price_match else "N/A"

                owner_match = re.search(r'Sale Price<\\/th>.*?Owner<\\/th>.*?class=\\"tm-wallet\\".*?short\\">(.*?)<\\/span>', response_text, re.DOTALL)
                owner = owner_match.group(1) if owner_match else "N/A"

                purchase_date_match = re.search(r'Purchased on <time datetime=\\"[^"]+\\">(.*?)<\\/time>', response_text, re.DOTALL)
                purchase_date = purchase_date_match.group(1) if purchase_date_match else "N/A"

                telegram_username_match = re.search(r'Telegram Username<\\/dt>.*?accent-color\\">@([^<]+)<', response_text, re.DOTALL)
                telegram_username = telegram_username_match.group(1) if telegram_username_match else "N/A"

                web_address_match = re.search(r'Web Address<\\/dt>.*?accent-color\\">t.me\\/([^<]+)<', response_text, re.DOTALL)
                web_address = web_address_match.group(1) if web_address_match else "N/A"

                result = (f"Sold\n"
                          f"Sale Price: {sale_price} TON\n"
                          f"Owner: {owner}\n"
                          f"Purchased on: {purchase_date}\n"
                          f"Telegram Username: @{telegram_username}\n"
                          f"Web Address: t.me/{web_address}")
            else:
                result = "No relevant information found."
        else:
            result = (f"Name part: {name_part}\n"
                      f"Minimum bid: {min_bid} TON\n"
                      f"Auction closing in: {auction_time}")

        await eor(e, result)
    else:
        await eor(e, f"Request failed with status code {response.status_code}")

# The function is now ready to be used in your bot.
