import re
import random
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector
from database import get_db, get_setting

USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Mobile Safari/537.36",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 17_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1"
]

def parse_telegram_link(link: str):
    """استخراج یوزرنیم کانال عمومی و آیدی پست از لینک"""
    match = re.search(r"(?:https?://)?(?:t\.me|telegram\.me)/([a-zA-Z0-9_]+)/(\d+)", link.strip())
    if not match:
        return None, None
    return match.group(1), int(match.group(2))

async def send_single_view(channel: str, post_id: int, proxy_url: str) -> bool:
    embed_url = f"https://t.me/{channel}/{post_id}?embed=1"
    headers = {
        "User-Agent": random.choice(USER_AGENTS),
        "Accept-Language": "en-US,en;q=0.9",
    }

    try:
        connector = None
        proxy_arg = None

        if proxy_url.startswith("socks"):
            connector = ProxyConnector.from_url(proxy_url)
        else:
            proxy_arg = proxy_url

        timeout = aiohttp.ClientTimeout(total=12)
        async with aiohttp.ClientSession(connector=connector, headers=headers, timeout=timeout) as session:
            async with session.get(embed_url, proxy=proxy_arg) as resp:
                if resp.status != 200:
                    return False
                html = await resp.text()

            match = re.search(r'data-view="([^"]+)"', html)
            if not match:
                return False

            view_token = match.group(1)
            view_url = f"https://t.me/v/?views={view_token}"
            post_headers = {
                "Referer": embed_url,
                "X-Requested-With": "XMLHttpRequest",
            }
            async with session.post(view_url, headers=post_headers, proxy=proxy_arg) as v_resp:
                text = await v_resp.text()
                return v_resp.status == 200 and "true" in text.lower()
    except Exception:
        return False

async def process_order_batch(order_id: int, batch_limit: int = 200):
    """پردازش یک دسته از سفارش (مناسب برای اجرای امن در هاست اشتراکی و سرور)"""
    conn = get_db()
    order = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
    proxies = [r["proxy_url"] for r in conn.execute("SELECT proxy_url FROM proxies WHERE is_active = 1").fetchall()]
    conn.close()

    if not order or not proxies:
        return 0

    ratio = float(get_setting("overdelivery_ratio", "1.15"))
    concurrency = int(get_setting("concurrency", "25"))
    target_total = int(order["quantity"] * ratio)
    remaining = max(0, target_total - order["sent"])

    if remaining <= 0:
        conn = get_db()
        conn.execute("UPDATE orders SET status = 'Completed' WHERE id = ?", (order_id,))
        conn.commit()
        conn.close()
        return 0

    to_send = min(remaining, batch_limit)
    semaphore = asyncio.Semaphore(concurrency)

    async def worker():
        async with semaphore:
            proxy = random.choice(proxies)
            return await send_single_view(order["channel"], order["post_id"], proxy)

    tasks = [asyncio.create_task(worker()) for _ in range(to_send)]
    results = await asyncio.gather(*tasks)
    success_count = sum(1 for r in results if r)

    new_sent = order["sent"] + success_count
    new_status = "Completed" if new_sent >= target_total else "In progress"

    conn = get_db()
    conn.execute("UPDATE orders SET sent = ?, status = ? WHERE id = ?", (new_sent, new_status, order_id))
    conn.commit()
    conn.close()
    return success_count

def run_pending_orders_sync(batch_limit: int = 150):
    """اجرای صف سفارش‌های باز (قابل صدا زدن از کرون‌جاب یا ترد پس‌زمینه)"""
    conn = get_db()
    orders = conn.execute(
        "SELECT id FROM orders WHERE status IN ('Pending', 'In progress') ORDER BY id ASC LIMIT 5"
    ).fetchall()
    conn.close()

    total_sent = 0
    for row in orders:
        total_sent += asyncio.run(process_order_batch(row["id"], batch_limit=batch_limit))
    return total_sent