print("shortlink.py loaded")

import aiohttp
from config import SHORT_URL, SHORT_API


# =========================
# GENERATE SHORTLINK
# =========================
async def generate_shortlink(url: str) -> str:

    if not SHORT_URL or not SHORT_API:
        return url

    try:
        api_url = f"https://{SHORT_URL}/api"

        timeout = aiohttp.ClientTimeout(total=10)

        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.get(
                api_url,
                params={
                    "api": SHORT_API,
                    "url": url
                }
            ) as response:

                if response.status != 200:
                    print("SHORTLINK HTTP ERROR:", response.status)
                    return url

                data = await response.json()

        short = (
            data.get("shortenedUrl")
            or data.get("short_url")
            or data.get("short")
            or data.get("url")
        )

        if short:
            print("SHORTLINK OK:", short)
            return short

        print("SHORTLINK EMPTY:", data)
        return url

    except Exception as e:
        print("SHORTLINK ERROR:", e)
        return url


# =========================
# BUILD VERIFY LINK
# =========================
def build_verify_link(bot_username: str, token: str) -> str:
    return f"https://t.me/{bot_username}?start=verify_{token}"