"""
╔══════════════════════════════════════════════════════════════════════════════╗
║         YouTube Automation Bot — FINAL VERSION (v2.0)                       ║
║         Stack: aiogram 3.x + Playwright-Stealth + SQLite + APScheduler     ║
╠══════════════════════════════════════════════════════════════════════════════╣
║  O'rnatish:                                                                 ║
║    pip install aiogram playwright aiosqlite python-dotenv                   ║
║               playwright-stealth apscheduler aiofiles                       ║
║    playwright install chromium                                               ║
║                                                                              ║
║  .env fayli:                                                                 ║
║    BOT_TOKEN=your_token                                                      ║
║    ADMIN_ID=123456789                                                        ║
║    DB_PATH=bot_database.db                                                   ║
║    HEADLESS=true                                                             ║
║    MAX_BROWSERS=3          # Parallel browser soni                           ║
║    LOG_LEVEL=INFO                                                            ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""

# ─────────────────────────────────────────────────────────────────────────────
#  IMPORTLAR
# ─────────────────────────────────────────────────────────────────────────────
import asyncio
import json
import logging
import os
import random
import sys
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from typing import Optional

import aiosqlite
from aiogram import Bot, Dispatcher, F, Router
from aiogram.exceptions import TelegramBadRequest
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import (
    BufferedInputFile,
    CallbackQuery,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    Message,
)
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from dotenv import load_dotenv
from playwright.async_api import BrowserContext, Page, async_playwright
# playwright_stealth versiyaga qarab import
try:
    from playwright_stealth import stealth_async          # v1.0.6 va undan eski
    _STEALTH_MODE = "async"
except ImportError:
    try:
        from playwright_stealth import Stealth            # yangi versiya
        _STEALTH_MODE = "new"
    except ImportError:
        _STEALTH_MODE = "none"
        logger = logging.getLogger("YTBot")
        logging.getLogger("YTBot").warning("⚠️ playwright_stealth o'rnatilmagan, stealth o'chirilgan.")

# ─────────────────────────────────────────────────────────────────────────────
#  KONFIGURATSIYA
# ─────────────────────────────────────────────────────────────────────────────
load_dotenv()

BOT_TOKEN=8314008584:AAGYO3-cfheu5m5IeE__YjtKTrFp392uiLc   # @BotFather dan 
ADMIN_ID=8221647864             # O'z Telegram ID ingiz
DB_PATH=bot_database.db
HEADLESS=true
MAX_BROWSERS=3000
LOG_LEVEL=INFO
# ─────────────────────────────────────────────────────────────────────────────
#  LOGGING
# ─────────────────────────────────────────────────────────────────────────────
logging.basicConfig(
    level=getattr(logging, LOG_LEVEL, logging.INFO),
    format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler("bot.log", encoding="utf-8"),
    ],
)
logger = logging.getLogger("YTBot")

# Aiogram ning keraksiz loglarini kamaytirish
logging.getLogger("aiogram").setLevel(logging.WARNING)
logging.getLogger("apscheduler").setLevel(logging.WARNING)

# ─────────────────────────────────────────────────────────────────────────────
#  KONSTANTALAR
# ─────────────────────────────────────────────────────────────────────────────
USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
]

BROWSER_ARGS = [
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--disable-blink-features=AutomationControlled",
    "--disable-dev-shm-usage",
    "--disable-infobars",
    "--disable-extensions",
    "--disable-gpu",
    "--disable-web-security",
    "--allow-running-insecure-content",
    "--no-first-run",
    "--no-default-browser-check",
    "--password-store=basic",
    "--use-mock-keychain",
    "--lang=en-US,en;q=0.9",
    "--accept-lang=en-US,en;q=0.9",
]

# Stealth init script
STEALTH_SCRIPT = """
(() => {
    // WebDriver belgisini o'chirish
    Object.defineProperty(navigator, 'webdriver', { get: () => undefined });

    // Chrome runtime simulatsiyasi
    if (!window.chrome) {
        window.chrome = {
            runtime: {
                onMessage: { addListener: () => {} },
                connect: () => ({ onMessage: { addListener: () => {} }, onDisconnect: { addListener: () => {} } }),
                sendMessage: () => {},
            },
            loadTimes: () => ({}),
            csi: () => ({}),
            app: {},
        };
    }

    // Plugin simulatsiyasi
    const pluginData = [
        { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
        { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '' },
        { name: 'Native Client', filename: 'internal-nacl-plugin', description: '' },
    ];
    Object.defineProperty(navigator, 'plugins', {
        get: () => {
            const arr = pluginData;
            arr.item = (i) => arr[i];
            arr.namedItem = (name) => arr.find(p => p.name === name);
            arr.refresh = () => {};
            return arr;
        }
    });

    // Til simulatsiyasi
    Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });

    // Hardware
    Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 8 });
    Object.defineProperty(navigator, 'deviceMemory', { get: () => 8 });

    // Permission API patch
    const origQuery = window.navigator.permissions?.query;
    if (origQuery) {
        window.navigator.permissions.query = (params) =>
            params.name === 'notifications'
                ? Promise.resolve({ state: Notification.permission })
                : origQuery(params);
    }

    // WebGL spoofing
    const getParam = WebGLRenderingContext.prototype.getParameter;
    WebGLRenderingContext.prototype.getParameter = function(param) {
        if (param === 37445) return 'Intel Inc.';
        if (param === 37446) return 'Intel Iris OpenGL Engine';
        return getParam.call(this, param);
    };
})();
"""

# ─────────────────────────────────────────────────────────────────────────────
#  MA'LUMOTLAR BAZASI
# ─────────────────────────────────────────────────────────────────────────────
async def init_db() -> None:
    """Barcha jadvallarni yaratish (mavjud bo'lmasa)."""
    async with aiosqlite.connect(DB_PATH) as db:
        await db.executescript("""
            PRAGMA journal_mode=WAL;
            PRAGMA foreign_keys=ON;

            CREATE TABLE IF NOT EXISTS accounts (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                email       TEXT    UNIQUE NOT NULL,
                password    TEXT    NOT NULL,
                cookies     TEXT    DEFAULT NULL,
                user_agent  TEXT    DEFAULT NULL,
                status      TEXT    DEFAULT 'active',
                added_date  TEXT    NOT NULL,
                last_check  TEXT    DEFAULT NULL,
                fail_count  INTEGER DEFAULT 0
            );

            CREATE TABLE IF NOT EXISTS subscriptions (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                account_id  INTEGER NOT NULL,
                channel_url TEXT    NOT NULL,
                sub_type    TEXT    NOT NULL,
                sub_date    TEXT    NOT NULL,
                unsub_date  TEXT    DEFAULT NULL,
                status      TEXT    DEFAULT 'active',
                FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS likes (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                account_id  INTEGER NOT NULL,
                video_url   TEXT    NOT NULL,
                liked_date  TEXT    NOT NULL,
                FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS task_history (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                task_type   TEXT    NOT NULL,
                target_url  TEXT    NOT NULL,
                total       INTEGER DEFAULT 0,
                success     INTEGER DEFAULT 0,
                fail        INTEGER DEFAULT 0,
                created_at  TEXT    NOT NULL
            );

            CREATE INDEX IF NOT EXISTS idx_accounts_status ON accounts(status);
            CREATE INDEX IF NOT EXISTS idx_subs_status ON subscriptions(status);
            CREATE INDEX IF NOT EXISTS idx_subs_unsub ON subscriptions(unsub_date);
        """)
        await db.commit()
    logger.info("✅ Ma'lumotlar bazasi tayyor (WAL mode, foreign keys ON).")


async def _fetchone(query: str, params: tuple = ()) -> Optional[any]:
    async with aiosqlite.connect(DB_PATH) as db:
        cur = await db.execute(query, params)
        return await cur.fetchone()


async def _fetchall(query: str, params: tuple = ()) -> list:
    async with aiosqlite.connect(DB_PATH) as db:
        db.row_factory = aiosqlite.Row
        cur = await db.execute(query, params)
        return await cur.fetchall()


async def _execute(query: str, params: tuple = ()) -> None:
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute(query, params)
        await db.commit()


async def db_upsert_account(email: str, password: str, cookies: list, user_agent: str) -> bool:
    try:
        async with aiosqlite.connect(DB_PATH) as db:
            await db.execute("""
                INSERT INTO accounts (email, password, cookies, user_agent, status, added_date, fail_count)
                VALUES (?, ?, ?, ?, 'active', ?, 0)
                ON CONFLICT(email) DO UPDATE SET
                    password=excluded.password,
                    cookies=excluded.cookies,
                    user_agent=excluded.user_agent,
                    status='active',
                    added_date=excluded.added_date,
                    fail_count=0
            """, (email, password, json.dumps(cookies), user_agent, datetime.now().isoformat()))
            await db.commit()
        return True
    except Exception as e:
        logger.error(f"db_upsert_account xato: {e}")
        return False


async def db_get_active_accounts(limit: Optional[int] = None) -> list:
    if limit:
        return await _fetchall(
            "SELECT * FROM accounts WHERE status='active' ORDER BY RANDOM() LIMIT ?", (limit,)
        )
    return await _fetchall("SELECT * FROM accounts WHERE status='active'")


async def db_count(table: str = "accounts", where: str = "1=1") -> int:
    row = await _fetchone(f"SELECT COUNT(*) FROM {table} WHERE {where}")
    return row[0] if row else 0


async def db_mark_dead(account_id: int) -> None:
    await _execute(
        "UPDATE accounts SET status='dead', last_check=?, fail_count=fail_count+1 WHERE id=?",
        (datetime.now().isoformat(), account_id)
    )


async def db_add_like(account_id: int, video_url: str) -> None:
    await _execute(
        "INSERT INTO likes (account_id, video_url, liked_date) VALUES (?,?,?)",
        (account_id, video_url, datetime.now().isoformat())
    )


async def db_add_subscription(account_id: int, channel_url: str, sub_type: str, unsub_date: Optional[datetime]) -> None:
    await _execute(
        "INSERT INTO subscriptions (account_id, channel_url, sub_type, sub_date, unsub_date, status) VALUES (?,?,?,?,?,?)",
        (account_id, channel_url, sub_type, datetime.now().isoformat(),
         unsub_date.isoformat() if unsub_date else None, "active")
    )


async def db_upcoming_unsubs() -> list:
    soon = (datetime.now() + timedelta(days=7)).isoformat()
    return await _fetchall("""
        SELECT s.*, a.email FROM subscriptions s
        JOIN accounts a ON s.account_id=a.id
        WHERE s.status='active' AND s.unsub_date IS NOT NULL AND s.unsub_date <= ?
        ORDER BY s.unsub_date ASC LIMIT 10
    """, (soon,))


async def db_get_expired_subs() -> list:
    now = datetime.now().isoformat()
    return await _fetchall("""
        SELECT s.*, a.email, a.cookies, a.user_agent FROM subscriptions s
        JOIN accounts a ON s.account_id=a.id
        WHERE s.status='active' AND s.unsub_date IS NOT NULL AND s.unsub_date <= ?
    """, (now,))


async def db_cancel_sub(sub_id: int) -> None:
    await _execute("UPDATE subscriptions SET status='cancelled' WHERE id=?", (sub_id,))


async def db_add_task_history(task_type: str, target_url: str, total: int, success: int, fail: int) -> None:
    await _execute(
        "INSERT INTO task_history (task_type, target_url, total, success, fail, created_at) VALUES (?,?,?,?,?,?)",
        (task_type, target_url, total, success, fail, datetime.now().isoformat())
    )


async def db_all_accounts() -> list:
    return await _fetchall("SELECT * FROM accounts ORDER BY id")


# ─────────────────────────────────────────────────────────────────────────────
#  PLAYWRIGHT YORDAMCHI FUNKSIYALAR
# ─────────────────────────────────────────────────────────────────────────────

@asynccontextmanager
async def new_browser_context(cookies: Optional[list] = None, user_agent: Optional[str] = None):
    """
    Har bir chaqiruvda BUTUNLAY IZOLYATSIYA qilingan brauzer ochadi.
    - Alohida user-data-dir (profil papkasi) — cookie, cache, history aralashmaydi
    - Tasodifiy viewport, User-Agent, timezone, til, ekran o'lchami
    - Har ochilganda yangi fingerprint — bir-biriga o'xshamaydi
    """
    import tempfile, shutil

    # Har sessiya uchun alohida vaqtinchalik profil papkasi
    profile_dir = tempfile.mkdtemp(prefix="yt_bot_profile_")

    # Tasodifiy xususiyatlar — har ochilganda o'zgaradi
    ua = user_agent or random.choice(USER_AGENTS)
    w  = random.randint(1240, 1440)
    h  = random.randint(700, 820)

    # Turli timezone'lar — har sessiya farqli joylashuvni ko'rsatadi
    timezones = [
        "America/New_York", "America/Chicago", "America/Los_Angeles",
        "America/Denver", "America/Phoenix", "Europe/London",
        "Europe/Berlin", "Europe/Paris", "America/Toronto",
    ]
    timezone = random.choice(timezones)

    # Turli til/locale kombinatsiyalari
    locales = ["en-US", "en-GB", "en-CA", "en-AU"]
    locale  = random.choice(locales)

    # Turli Chrome versiyalari uchun Sec-CH-UA
    chrome_versions = ["120", "121", "122", "123", "124"]
    cv = random.choice(chrome_versions)
    sec_ch_ua = f'"Not A(Brand";v="99", "Google Chrome";v="{cv}", "Chromium";v="{cv}"'

    try:
        async with async_playwright() as p:
            browser = await p.chromium.launch_persistent_context(
                user_data_dir=profile_dir,
                headless=HEADLESS,
                args=BROWSER_ARGS + [
                    f"--window-size={w},{h}",
                    f"--window-position={random.randint(0,100)},{random.randint(0,60)}",
                    "--disable-features=IsolateOrigins,site-per-process",
                    "--disable-site-isolation-trials",
                ],
                viewport={"width": w, "height": h},
                user_agent=ua,
                locale=locale,
                timezone_id=timezone,
                color_scheme="light",
                java_script_enabled=True,
                accept_downloads=False,
                extra_http_headers={
                    "Accept-Language": f"{locale},{locale[:2]};q=0.9",
                    "Accept-Encoding": "gzip, deflate, br",
                    "DNT": str(random.randint(0, 1)),
                    "Sec-CH-UA": sec_ch_ua,
                    "Sec-CH-UA-Mobile": "?0",
                    "Sec-CH-UA-Platform": '"Windows"',
                },

            )

            # Stealth script + har sessiya uchun tasodifiy canvas fingerprint
            avail_h      = h - random.randint(40, 80)
            unique_noise = random.randint(1, 99)
            await browser.add_init_script(STEALTH_SCRIPT)
            await browser.add_init_script(f"""
                (() => {{
                    // Canvas fingerprint — har sessiyada farqli
                    const noise = {unique_noise};
                    const origToDataURL = HTMLCanvasElement.prototype.toDataURL;
                    HTMLCanvasElement.prototype.toDataURL = function(type) {{
                        const ctx = this.getContext('2d');
                        if (ctx) {{
                            const imageData = ctx.getImageData(0, 0, this.width, this.height);
                            for (let i = 0; i < imageData.data.length; i += 100) {{
                                imageData.data[i] = imageData.data[i] ^ (noise & 0xff);
                            }}
                            ctx.putImageData(imageData, 0, 0);
                        }}
                        return origToDataURL.call(this, type);
                    }};

                    // Screen o'lchami simulatsiyasi
                    Object.defineProperty(screen, 'width',       {{ get: () => {w} }});
                    Object.defineProperty(screen, 'height',      {{ get: () => {h} }});
                    Object.defineProperty(screen, 'availWidth',  {{ get: () => {w} }});
                    Object.defineProperty(screen, 'availHeight', {{ get: () => {avail_h} }});

                    // Timezone
                    Intl.DateTimeFormat = new Proxy(Intl.DateTimeFormat, {{
                        construct(target, args) {{
                            if (!args[1]) args[1] = {{}};
                            if (!args[1].timeZone) args[1].timeZone = '{timezone}';
                            return new target(...args);
                        }}
                    }});
                }})();
            """)

            if cookies:
                await browser.add_cookies(cookies)

            try:
                yield browser, browser, ua   # persistent context = context + browser
            finally:
                await browser.close()

    finally:
        # Profil papkasini o'chirish — hech qanday iz qolmaydi
        try:
            shutil.rmtree(profile_dir, ignore_errors=True)
        except Exception:
            pass


async def _human_type(element, text: str) -> None:
    """Inson kabi sekin, real klaviatura bosishlari bilan yozish."""
    for char in text:
        await element.type(char, delay=random.randint(60, 200))
        if random.random() < 0.05:
            await asyncio.sleep(random.uniform(0.1, 0.4))


async def _apply_stealth(page) -> None:
    """playwright_stealth versiyasiga qarab stealth qo'llash."""
    if _STEALTH_MODE == "async":
        try:
            await stealth_async(page)
        except Exception:
            pass
    elif _STEALTH_MODE == "new":
        try:
            async with Stealth() as stealth:
                await stealth.apply_stealth_async(page)
        except Exception:
            try:
                stealth = Stealth()
                await stealth.apply_stealth_async(page)
            except Exception:
                pass
    # "none" — stealth qo'llanmaydi, davom etiladi


async def _safe_click(page: Page, selector: str, timeout: int = 5000) -> bool:
    """Xavfsiz click — topilmasa False qaytaradi."""
    try:
        btn = await page.wait_for_selector(selector, state="visible", timeout=timeout)
        if btn:
            await asyncio.sleep(random.uniform(0.3, 0.8))
            await btn.click()
            return True
    except Exception:
        pass
    return False


async def google_login(email: str, password: str) -> tuple[Optional[list], Optional[str], Optional[str]]:
    """
    Google akkauntiga kirish va cookie olish.
    MANUAL MODE: Brauzer ochiladi, foydalanuvchi o'zi kiradi, cookie saqlanadi.
    Returns: (cookies, user_agent, error_reason)
    """
    error_reason = "Noma'lum xato"

    try:
        async with async_playwright() as p:
            ua = random.choice(USER_AGENTS)

            # Har doim ko'rinadigan brauzer (HEADLESS=false) — Google botni bloklaydi
            browser = await p.chromium.launch(
                headless=False,   # <-- majburiy, Google uchun
                args=BROWSER_ARGS
            )
            context = await browser.new_context(
                viewport={"width": 1280, "height": 720},
                user_agent=ua,
                locale="en-US",
                timezone_id="America/New_York",
            )
            await context.add_init_script(STEALTH_SCRIPT)
            page = await context.new_page()

            logger.info(f"🌐 Brauzer ochildi: {email} — o'zingiz kiring!")

            # Google sign-in sahifasiga o'tish
            await page.goto(
                "https://accounts.google.com/signin/v2/identifier"
                "?flowName=GlifWebSignIn&flowEntry=ServiceLogin",
                wait_until="domcontentloaded",
                timeout=60_000
            )

            # Email avtomatik yozish (lekin Google bloklamasligi uchun sekin)
            try:
                email_input = await page.wait_for_selector(
                    'input[type="email"]', state="visible", timeout=15_000
                )
                await asyncio.sleep(random.uniform(1.0, 2.0))
                await email_input.click()
                await asyncio.sleep(0.5)
                await _human_type(email_input, email)
                await asyncio.sleep(random.uniform(0.8, 1.5))
                if not await _safe_click(page, '#identifierNext button, #identifierNext'):
                    await page.keyboard.press("Enter")
                await asyncio.sleep(random.uniform(2.0, 3.5))
            except Exception:
                pass  # Agar avtomatik ishlamasa, foydalanuvchi qo'lda kiradi

            # Parolni avtomatik yozish
            try:
                pwd_input = await page.wait_for_selector(
                    'input[type="password"]', state="visible", timeout=10_000
                )
                await asyncio.sleep(random.uniform(0.8, 1.5))
                await pwd_input.click()
                await _human_type(pwd_input, password)
                await asyncio.sleep(random.uniform(0.8, 1.2))
                if not await _safe_click(page, '#passwordNext button, #passwordNext'):
                    await page.keyboard.press("Enter")
            except Exception:
                pass  # Foydalanuvchi qo'lda davom ettiradi

            # Foydalanuvchi kirguncha kutish (max 3 daqiqa)
            logger.info("⏳ Google sahifasida kiring... Bot 3 daqiqa kutadi.")
            deadline = asyncio.get_event_loop().time() + 180  # 3 daqiqa

            while asyncio.get_event_loop().time() < deadline:
                await asyncio.sleep(3)
                current_url = page.url
                cookies = await context.cookies()
                google_cookies = [c for c in cookies if ".google.com" in c.get("domain", "")]

                # Muvaffaqiyat tekshiruvi
                success_domains = ["myaccount.google.com", "youtube.com", "mail.google.com"]
                if any(d in current_url for d in success_domains):
                    logger.info(f"✅ Login muvaffaqiyatli: {email} | {len(cookies)} cookie")
                    await browser.close()
                    return cookies, ua, None

                if len(google_cookies) > 8 and "accounts.google.com" not in current_url:
                    logger.info(f"✅ Login muvaffaqiyatli (cookie): {email}")
                    await browser.close()
                    return cookies, ua, None

                # Hali signin sahifasida emasmi tekshirish
                if "accounts.google.com" not in current_url and "google.com" in current_url:
                    logger.info(f"✅ Login muvaffaqiyatli (redirect): {email}")
                    await browser.close()
                    return cookies, ua, None

            # 3 daqiqa o'tdi
            await browser.close()
            return None, None, "Vaqt tugadi — 3 daqiqa ichida kira olmadi"

    except Exception as e:
        logger.error(f"google_login kritik xato [{email}]: {e}", exc_info=True)
        return None, None, f"Texnik xato: {str(e)[:120]}"


async def youtube_like_video(video_url: str, cookies: list, user_agent: str) -> bool:
    """
    YouTube videoga Like bosish.
    Returns: True (muvaffaqiyat) | False (xato)
    """
    try:
        async with new_browser_context(cookies=cookies, user_agent=user_agent) as (context, browser, _):
            page = await context.new_page()
            await _apply_stealth(page)

            # Shorts va oddiy video URL ni normallashtirish
            await page.goto(video_url, wait_until="networkidle", timeout=90_000)
            await asyncio.sleep(random.uniform(4, 7))

            # Login tekshiruvi — cookie ishlaymaptimi?
            current_url = page.url
            if "accounts.google.com" in current_url or "signin" in current_url:
                logger.warning(f"⚠️ Cookie eskirgan — login sahifasiga yo'naltirildi")
                return False

            # Scroll — video yuklangach
            await page.evaluate("window.scrollBy(0, 200)")
            await asyncio.sleep(random.uniform(2, 3))

            # Keng qamrovli like selectorlari (2024-2025 YouTube interfeysi)
            like_selectors = [
                # Yangi interfeys (2024+)
                'like-button-view-model button',
                'segmented-like-dislike-button-view-model like-button-view-model button',
                # Shorts uchun
                'ytd-reel-player-overlay-renderer like-button-view-model button',
                '#like-button button',
                # Eski interfeys
                'ytd-toggle-button-renderer.ytd-menu-renderer:first-child button',
                '#top-level-buttons-computed > ytd-toggle-button-renderer:first-child button',
                # aria-label orqali
                'button[aria-label*="like this video"]',
                'button[aria-label*="Like this video"]',
                'button[aria-label*="I like this"]',
                # title orqali
                'button[title="Like"]',
            ]

            for selector in like_selectors:
                try:
                    btn = await page.wait_for_selector(selector, state="visible", timeout=3_000)
                    if not btn:
                        continue

                    aria_pressed = await btn.get_attribute("aria-pressed")
                    aria_label   = (await btn.get_attribute("aria-label") or "").lower()

                    # Allaqachon like bosilgan
                    if aria_pressed == "true" or "unlike" in aria_label or "remove like" in aria_label:
                        logger.info(f"✅ Allaqachon like bosilgan: {video_url}")
                        return True

                    # Like bosish
                    await asyncio.sleep(random.uniform(0.8, 2.0))
                    await btn.scroll_into_view_if_needed()
                    await btn.click()
                    await asyncio.sleep(random.uniform(2.0, 3.5))

                    # Tasdiqlash — aria-pressed true bo'ldimi?
                    aria_after = await btn.get_attribute("aria-pressed")
                    if aria_after == "true":
                        logger.info(f"👍 Like bosildi [{selector}]: {video_url}")
                        return True
                    else:
                        logger.info(f"👍 Like bosildi (click yuborildi): {video_url}")
                        return True

                except Exception:
                    continue

            # JavaScript orqali urinib ko'rish (fallback)
            try:
                result = await page.evaluate("""
                    () => {
                        const selectors = [
                            'like-button-view-model button',
                            'button[aria-label*="like"]',
                            'button[title="Like"]',
                        ];
                        for (const sel of selectors) {
                            const btn = document.querySelector(sel);
                            if (btn && btn.getAttribute('aria-pressed') !== 'true') {
                                btn.click();
                                return true;
                            }
                        }
                        return false;
                    }
                """)
                if result:
                    await asyncio.sleep(2)
                    logger.info(f"👍 Like bosildi (JS fallback): {video_url}")
                    return True
            except Exception:
                pass

            logger.warning(f"⚠️ Like tugmasi topilmadi: {video_url}")
            return False

    except Exception as e:
        logger.error(f"youtube_like_video xato: {e}", exc_info=True)
        return False


async def youtube_subscribe(channel_url: str, cookies: list, user_agent: str) -> bool:
    """
    YouTube kanaliga obuna bo'lish.
    Returns: True | False
    """
    try:
        async with new_browser_context(cookies=cookies, user_agent=user_agent) as (context, browser, _):
            page = await context.new_page()
            await _apply_stealth(page)

            await page.goto(channel_url, wait_until="domcontentloaded", timeout=60_000)
            await asyncio.sleep(random.uniform(3, 6))

            sub_selectors = [
                'yt-subscribe-button-view-model button',
                '#subscribe-button yt-button-shape button',
                '#subscribe-button button',
                'tp-yt-paper-button#subscribe',
                '[aria-label*="Subscribe"]',
            ]

            for selector in sub_selectors:
                try:
                    btn = await page.wait_for_selector(selector, state="visible", timeout=5_000)
                    if not btn:
                        continue
                    text = (await btn.inner_text()).strip().lower()
                    aria = (await btn.get_attribute("aria-label") or "").lower()

                    if "subscribed" in text or "unsubscribe" in aria:
                        logger.debug(f"✅ Allaqachon obuna: {channel_url}")
                        return True

                    await asyncio.sleep(random.uniform(0.5, 1.5))
                    await btn.click()
                    await asyncio.sleep(random.uniform(2.0, 3.5))
                    logger.debug(f"🔔 Obuna bo'ldi: {channel_url}")
                    return True
                except Exception:
                    continue

            logger.warning(f"⚠️ Subscribe tugmasi topilmadi: {channel_url}")
            return False

    except Exception as e:
        logger.error(f"youtube_subscribe xato: {e}")
        return False


async def youtube_unsubscribe(channel_url: str, cookies: list, user_agent: str) -> bool:
    """
    YouTube kanaldan obunani bekor qilish.
    Returns: True | False
    """
    try:
        async with new_browser_context(cookies=cookies, user_agent=user_agent) as (context, browser, _):
            page = await context.new_page()
            await _apply_stealth(page)

            await page.goto(channel_url, wait_until="domcontentloaded", timeout=60_000)
            await asyncio.sleep(random.uniform(3, 5))

            selectors = [
                'yt-subscribe-button-view-model button',
                '#subscribe-button button',
            ]

            for selector in selectors:
                try:
                    btn = await page.wait_for_selector(selector, state="visible", timeout=5_000)
                    if not btn:
                        continue
                    text = (await btn.inner_text()).strip().lower()
                    aria = (await btn.get_attribute("aria-label") or "").lower()

                    if "subscribed" in text or "unsubscribe" in aria:
                        await btn.click()
                        await asyncio.sleep(random.uniform(1.5, 2.5))
                        # Tasdiqlash dialogi
                        try:
                            confirm = await page.wait_for_selector(
                                'yt-button-renderer#confirm-button button, '
                                'button[aria-label*="Unsubscribe"]',
                                timeout=3_000
                            )
                            if confirm:
                                await confirm.click()
                                await asyncio.sleep(1)
                        except Exception:
                            pass
                        logger.debug(f"🔕 Obuna bekor qilindi: {channel_url}")
                        return True
                except Exception:
                    continue

            logger.warning(f"⚠️ Unsubscribe tugmasi topilmadi: {channel_url}")
            return False

    except Exception as e:
        logger.error(f"youtube_unsubscribe xato: {e}")
        return False


async def run_parallel_task(coro_factory, accounts: list, semaphore_limit: int):
    """
    Akkauntlar ro'yxati uchun vazifalarni parallel bajarish.
    Returns: (success_count, fail_count)
    """
    semaphore = asyncio.Semaphore(semaphore_limit)
    success_count = 0
    fail_count = 0
    lock = asyncio.Lock()

    async def bounded_task(acc):
        nonlocal success_count, fail_count
        async with semaphore:
            result = await coro_factory(acc)
            async with lock:
                if result:
                    success_count += 1
                else:
                    fail_count += 1

    await asyncio.gather(*[bounded_task(acc) for acc in accounts], return_exceptions=True)
    return success_count, fail_count


# ─────────────────────────────────────────────────────────────────────────────
#  FSM HOLATLARI
# ─────────────────────────────────────────────────────────────────────────────
class AddAccount(StatesGroup):
    waiting_email    = State()
    waiting_password = State()
    confirming       = State()


class LikeService(StatesGroup):
    waiting_link  = State()
    waiting_count = State()


class SubService(StatesGroup):
    waiting_period  = State()
    waiting_link    = State()
    waiting_count   = State()


# ─────────────────────────────────────────────────────────────────────────────
#  KLAVIATURALAR
# ─────────────────────────────────────────────────────────────────────────────
def kb(*rows):
    """Inline klaviatura yaratuvchi yordamchi."""
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text=text, callback_data=data) for text, data in row]
        for row in rows
    ])


MAIN_MENU_KB = kb(
    [("➕ Akkaunt qo'shish", "add_account")],
    [("🛠 Xizmatlar",         "services")],
    [("📊 Statistika",        "statistics")],
    [("📋 Akkauntlar",        "list_accounts")],
    [("ℹ️ Yordam",             "help")],
)

SERVICES_KB = kb(
    [("👍 YouTube Like",  "yt_like"),  ("🔔 YouTube Obuna", "yt_sub")],
    [("🔙 Orqaga",        "back_main")],
)

SUB_PERIOD_KB = kb(
    [("15 kun", "period_15"),   ("30 kun",  "period_30")],
    [("60 kun", "period_60"),   ("90 kun",  "period_90")],
    [("360 kun", "period_360"), ("♾ Umrbod", "period_forever")],
    [("🔙 Orqaga", "services")],
)

CONFIRM_KB = kb(
    [("✅ Ha, kirish", "confirm_login"), ("❌ Bekor", "cancel_login")],
)

BACK_MAIN_KB = kb([("🏠 Bosh menyu", "back_main")])


# ─────────────────────────────────────────────────────────────────────────────
#  YORDAMCHI FUNKSIYALAR
# ─────────────────────────────────────────────────────────────────────────────
def is_admin(user_id: int) -> bool:
    return user_id == ADMIN_ID


async def edit_or_send(msg: Message, text: str, **kwargs) -> Message:
    """Xabarni tahrirlash, imkonsiz bo'lsa yangisini yuborish."""
    try:
        return await msg.edit_text(text, **kwargs)
    except TelegramBadRequest:
        return await msg.answer(text, **kwargs)


def now_str() -> str:
    return datetime.now().strftime("%d.%m.%Y %H:%M:%S")


def is_youtube_url(url: str) -> bool:
    return "youtube.com" in url or "youtu.be" in url


# ─────────────────────────────────────────────────────────────────────────────
#  ROUTER VA HANDLERLAR
# ─────────────────────────────────────────────────────────────────────────────
router = Router()


# ──────────── GUARD ────────────
async def admin_guard(event, state: FSMContext) -> bool:
    """Admin emaslarga javob beruvchi dekorator o'rniga funksiya."""
    uid = event.from_user.id if hasattr(event, "from_user") else None
    if uid and not is_admin(uid):
        if isinstance(event, CallbackQuery):
            await event.answer("⛔ Sizda ruxsat yo'q.", show_alert=True)
        else:
            await event.answer("⛔ Sizda ruxsat yo'q.")
        return False
    return True


# ──────────── /start ────────────
@router.message(Command("start"))
async def cmd_start(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        await msg.answer("⛔ Sizda ruxsat yo'q.")
        return
    await state.clear()
    active = await db_count("accounts", "status='active'")
    await msg.answer(
        f"🤖 <b>YouTube Automation Bot</b> <i>v2.0</i>\n\n"
        f"👋 Xush kelibsiz, admin!\n"
        f"📊 Hozirda faol akkauntlar: <b>{active} ta</b>\n\n"
        "Quyidagi bo'limlardan birini tanlang:",
        parse_mode="HTML",
        reply_markup=MAIN_MENU_KB
    )


# ──────────── /stats ────────────
@router.message(Command("stats"))
async def cmd_stats(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    await show_statistics(msg)


# ──────────── Bosh menyu ────────────
@router.callback_query(F.data == "back_main")
async def cb_back_main(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    await state.clear()
    active = await db_count("accounts", "status='active'")
    await cb.message.edit_text(
        f"🤖 <b>YouTube Automation Bot</b> <i>v2.0</i>\n\n"
        f"📊 Faol akkauntlar: <b>{active} ta</b>\n\n"
        "Quyidagi bo'limlardan birini tanlang:",
        parse_mode="HTML",
        reply_markup=MAIN_MENU_KB
    )
    await cb.answer()


# ──────────── YORDAM ────────────
@router.callback_query(F.data == "help")
async def cb_help(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    await cb.message.edit_text(
        "ℹ️ <b>Yordam — YouTube Automation Bot</b>\n\n"
        "<b>📌 Asosiy buyruqlar:</b>\n"
        "/start — Bosh menyu\n"
        "/stats — Tezkor statistika\n\n"
        "<b>🔄 Xizmatlar:</b>\n"
        "• <b>YouTube Like</b> — Tanlangan videoga akkauntlardan like bosadi\n"
        "• <b>YouTube Obuna</b> — Tanlangan kanalga muddatli yoki umrbod obuna qo'shadi\n\n"
        "<b>⏰ Avtomatik:</b>\n"
        "• Har 1 soatda muddati o'tgan obunalar avtomatik bekor qilinadi\n\n"
        "<b>⚠️ Muhim:</b>\n"
        "• 2FA o'chirilgan Gmail akkauntlari ishlatiladi\n"
        "• HEADLESS=false qo'yib vizual sinash mumkin\n"
        "• Cookie 30-60 kun davomida ishlashi mumkin",
        parse_mode="HTML",
        reply_markup=BACK_MAIN_KB
    )
    await cb.answer()


# ──────────── AKKAUNT QO'SHISH ────────────
@router.callback_query(F.data == "add_account")
async def cb_add_account(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    await state.set_state(AddAccount.waiting_email)
    await cb.message.edit_text(
        "➕ <b>Yangi akkaunt qo'shish</b>\n\n"
        "📧 Gmail manzilingizni kiriting:\n"
        "<i>Misol: example@gmail.com</i>\n\n"
        "❌ Bekor qilish uchun /start bosing.",
        parse_mode="HTML"
    )
    await cb.answer()


@router.message(AddAccount.waiting_email)
async def process_email(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    email = msg.text.strip().lower()
    if "@" not in email or "." not in email.split("@")[-1]:
        await msg.answer(
            "❌ <b>Noto'g'ri email format.</b>\n"
            "To'g'ri format: <code>example@gmail.com</code>",
            parse_mode="HTML"
        )
        return
    await state.update_data(email=email)
    await state.set_state(AddAccount.waiting_password)
    await msg.answer(
        f"✅ Email: <code>{email}</code>\n\n"
        "🔑 Endi Google parolini kiriting:\n"
        "<i>(Xabar yuborilgandan keyin avtomatik o'chirilmaydi, ehtiyot bo'ling)</i>",
        parse_mode="HTML"
    )


@router.message(AddAccount.waiting_password)
async def process_password(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    password = msg.text.strip()
    if len(password) < 6:
        await msg.answer("❌ Parol juda qisqa. Kamida 6 ta belgi bo'lishi kerak:")
        return
    await state.update_data(password=password)
    data = await state.get_data()
    await state.set_state(AddAccount.confirming)
    await msg.answer(
        f"📋 <b>Tasdiqlash</b>\n\n"
        f"📧 Email:  <code>{data['email']}</code>\n"
        f"🔑 Parol:  <code>{'●' * len(password)}</code>\n\n"
        "⚠️ Google akkauntiga kirish boshlana. Davom etilsinmi?",
        parse_mode="HTML",
        reply_markup=CONFIRM_KB
    )


@router.callback_query(F.data == "confirm_login")
async def cb_confirm_login(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    data = await state.get_data()
    email    = data.get("email")
    password = data.get("password")

    if not email or not password:
        await cb.message.edit_text("❌ Ma'lumot topilmadi. /start bosing.")
        await state.clear()
        try:
            await cb.answer()
        except Exception:
            pass
        return

    # Callback ni DARHOL yopamiz (Telegram 10 sek timeout)
    try:
        await cb.answer("⏳ Jarayon boshlandi, kuting...")
    except Exception:
        pass

    await cb.message.edit_text(
        f"⏳ <b>Jarayon boshlandi...</b>\n\n"
        f"🌐 Kirish: <code>{email}</code>\n"
        f"🔄 Stealth brauzer ishga tushmoqda...\n\n"
        "⚠️ <i>Bu jarayon 30–90 soniya olishi mumkin. Kuting...</i>",
        parse_mode="HTML"
    )

    cookies, user_agent, error_reason = await google_login(email, password)

    if cookies and user_agent:
        success = await db_upsert_account(email, password, cookies, user_agent)
        if success:
            active_count = await db_count("accounts", "status='active'")
            await cb.message.edit_text(
                f"✅ <b>Muvaffaqiyatli qo'shildi!</b>\n\n"
                f"📧 Akkaunt: <code>{email}</code>\n"
                f"🍪 Cookie saqlandi\n"
                f"🔒 User-Agent saqlandi\n"
                f"📊 Jami faol akkauntlar: <b>{active_count} ta</b>\n"
                f"🕐 {now_str()}",
                parse_mode="HTML",
                reply_markup=BACK_MAIN_KB
            )
            logger.info(f"✅ Yangi akkaunt qo'shildi: {email}")
        else:
            await cb.message.edit_text(
                "❌ Bazaga saqlashda xato yuz berdi.",
                reply_markup=BACK_MAIN_KB
            )
    else:
        reason_text = f"\n\n🔍 <b>Sabab:</b> <i>{error_reason}</i>" if error_reason else ""
        await cb.message.edit_text(
            f"❌ <b>Kirish muvaffaqiyatsiz!</b>\n\n"
            f"📧 Email: <code>{email}</code>"
            f"{reason_text}\n\n"
            "💡 <b>Mumkin bo'lgan yechimlar:</b>\n"
            "• Gmail parolini tekshiring\n"
            "• Ikki qadam tekshiruvini (2FA) o'chiring\n"
            "• <a href='https://myaccount.google.com/security'>Google Security</a> sahifasini tekshiring\n"
            "• HEADLESS=false qo'yib vizual sinang\n"
            "• Akkaunt bloklangan bo'lishi mumkin",
            parse_mode="HTML",
            reply_markup=BACK_MAIN_KB,
            disable_web_page_preview=True
        )

    await state.clear()


@router.callback_query(F.data == "cancel_login")
async def cb_cancel_login(cb: CallbackQuery, state: FSMContext):
    await state.clear()
    await cb.message.edit_text("❌ Bekor qilindi.", reply_markup=BACK_MAIN_KB)
    await cb.answer()


# ──────────── XIZMATLAR ────────────
@router.callback_query(F.data == "services")
async def cb_services(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    await state.clear()
    active = await db_count("accounts", "status='active'")
    await cb.message.edit_text(
        f"🛠 <b>Xizmatlar</b>\n\n"
        f"📊 Bazada faol akkaunt: <b>{active} ta</b>\n\n"
        "Qaysi xizmatdan foydalanmoqchisiz?",
        parse_mode="HTML",
        reply_markup=SERVICES_KB
    )
    await cb.answer()


# ──────────── YOUTUBE LIKE ────────────
@router.callback_query(F.data == "yt_like")
async def cb_yt_like(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    active = await db_count("accounts", "status='active'")
    if active == 0:
        await cb.message.edit_text(
            "❌ Bazada faol akkaunt yo'q.\n\n"
            "Avval ➕ Akkaunt qo'shish orqali akkaunt kiriting.",
            reply_markup=BACK_MAIN_KB
        )
        return
    await cb.answer()
    await state.set_state(LikeService.waiting_link)
    await cb.message.edit_text(
        f"👍 <b>YouTube Like xizmati</b>\n\n"
        f"📊 Faol akkauntlar: <b>{active} ta</b>\n\n"
        "🔗 YouTube video linkini yuboring:\n"
        "<i>Misol: https://youtube.com/watch?v=...</i>",
        parse_mode="HTML"
    )
    await cb.answer()


@router.message(LikeService.waiting_link)
async def process_like_link(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    link = msg.text.strip()
    if not is_youtube_url(link):
        await msg.answer(
            "❌ <b>Bu YouTube linki emas.</b>\n"
            "To'g'ri link yuboring (youtube.com yoki youtu.be):",
            parse_mode="HTML"
        )
        return
    await state.update_data(video_url=link)
    active = await db_count("accounts", "status='active'")
    await state.set_state(LikeService.waiting_count)
    await msg.answer(
        f"✅ Link qabul qilindi.\n\n"
        f"📊 Bazada <b>{active} ta</b> faol akkaunt mavjud.\n"
        f"Nechta Like bosmoqchisiz? (1 — {active}):",
        parse_mode="HTML"
    )


@router.message(LikeService.waiting_count)
async def process_like_count(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    try:
        count = int(msg.text.strip())
        assert count > 0
    except (ValueError, AssertionError):
        await msg.answer("❌ Musbat son kiriting:")
        return

    active = await db_count("accounts", "status='active'")
    if count > active:
        await msg.answer(f"❌ Bazada faqat <b>{active} ta</b> faol akkaunt bor.", parse_mode="HTML")
        return

    data = await state.get_data()
    video_url = data["video_url"]
    await state.clear()

    status_msg = await msg.answer(
        f"⏳ <b>Like jarayoni boshlandi!</b>\n\n"
        f"🎬 Video: <a href='{video_url}'>link</a>\n"
        f"👍 Maqsad: <b>{count} ta</b> like\n"
        f"⚙️ Parallel browserlar: <b>{MAX_BROWSERS}</b>\n"
        f"🔄 Bajarilmoqda...",
        parse_mode="HTML",
        disable_web_page_preview=True
    )

    accounts = await db_get_active_accounts(limit=count)

    async def like_task(acc):
        cookies    = json.loads(acc["cookies"])
        ua         = acc["user_agent"]
        result     = await youtube_like_video(video_url, cookies, ua)
        if result:
            await db_add_like(acc["id"], video_url)
        else:
            await db_mark_dead(acc["id"])
        return result

    success_count, fail_count = await run_parallel_task(like_task, accounts, MAX_BROWSERS)
    total_likes = await db_count("likes")

    await db_add_task_history("like", video_url, count, success_count, fail_count)

    await status_msg.edit_text(
        f"✅ <b>Like jarayoni yakunlandi!</b>\n\n"
        f"🎬 Video: <a href='{video_url}'>link</a>\n"
        f"{'─' * 28}\n"
        f"✅ Muvaffaqiyatli: <b>{success_count} ta</b>\n"
        f"❌ Xato / o'lik akkaunt: <b>{fail_count} ta</b>\n"
        f"{'─' * 28}\n"
        f"📊 Bot jami like: <b>{total_likes} ta</b>\n"
        f"🕐 {now_str()}",
        parse_mode="HTML",
        reply_markup=BACK_MAIN_KB,
        disable_web_page_preview=True
    )


# ──────────── YOUTUBE OBUNA ────────────
@router.callback_query(F.data == "yt_sub")
async def cb_yt_sub(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    active = await db_count("accounts", "status='active'")
    if active == 0:
        await cb.message.edit_text(
            "❌ Bazada faol akkaunt yo'q.",
            reply_markup=BACK_MAIN_KB
        )
        return
    await cb.answer()
    await state.set_state(SubService.waiting_period)
    await cb.message.edit_text(
        f"🔔 <b>YouTube Obuna xizmati</b>\n\n"
        f"📊 Faol akkauntlar: <b>{active} ta</b>\n\n"
        "⏱ Obuna muddatini tanlang:",
        parse_mode="HTML",
        reply_markup=SUB_PERIOD_KB
    )
    await cb.answer()


@router.callback_query(F.data.startswith("period_"))
async def cb_period(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return

    period_map = {
        "period_15":      ("15 kun",  15),
        "period_30":      ("30 kun",  30),
        "period_60":      ("60 kun",  60),
        "period_90":      ("90 kun",  90),
        "period_360":     ("360 kun", 360),
        "period_forever": ("♾ Umrbod", None),
    }

    period_label, period_days = period_map.get(cb.data, ("Noma'lum", None))
    await state.update_data(period_label=period_label, period_days=period_days)
    await state.set_state(SubService.waiting_link)

    await cb.message.edit_text(
        f"✅ Muddat tanlandi: <b>{period_label}</b>\n\n"
        "🔗 YouTube kanal linkini yuboring:\n"
        "<i>Misol: https://youtube.com/@channelname</i>",
        parse_mode="HTML"
    )
    await cb.answer()


@router.message(SubService.waiting_link)
async def process_sub_link(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    link = msg.text.strip()
    if not is_youtube_url(link):
        await msg.answer(
            "❌ <b>Bu YouTube linki emas.</b>\n"
            "To'g'ri kanal linkini yuboring:",
            parse_mode="HTML"
        )
        return
    await state.update_data(channel_url=link)
    active = await db_count("accounts", "status='active'")
    await state.set_state(SubService.waiting_count)
    await msg.answer(
        f"✅ Kanal link qabul qilindi.\n\n"
        f"📊 Bazada <b>{active} ta</b> faol akkaunt mavjud.\n"
        f"Nechta akkauntdan obuna bo'lmoqchisiz? (1 — {active}):",
        parse_mode="HTML"
    )


@router.message(SubService.waiting_count)
async def process_sub_count(msg: Message, state: FSMContext):
    if not is_admin(msg.from_user.id):
        return
    try:
        count = int(msg.text.strip())
        assert count > 0
    except (ValueError, AssertionError):
        await msg.answer("❌ Musbat son kiriting:")
        return

    active = await db_count("accounts", "status='active'")
    if count > active:
        await msg.answer(f"❌ Bazada faqat <b>{active} ta</b> faol akkaunt bor.", parse_mode="HTML")
        return

    data = await state.get_data()
    channel_url  = data["channel_url"]
    period_days  = data["period_days"]
    period_label = data["period_label"]
    await state.clear()

    unsub_date = datetime.now() + timedelta(days=period_days) if period_days else None

    status_msg = await msg.answer(
        f"⏳ <b>Obuna jarayoni boshlandi!</b>\n\n"
        f"📺 Kanal: <a href='{channel_url}'>link</a>\n"
        f"⏱ Muddat: <b>{period_label}</b>\n"
        f"👥 Akkauntlar: <b>{count} ta</b>\n"
        f"⚙️ Parallel browserlar: <b>{MAX_BROWSERS}</b>\n"
        f"🔄 Bajarilmoqda...",
        parse_mode="HTML",
        disable_web_page_preview=True
    )

    accounts = await db_get_active_accounts(limit=count)

    async def sub_task(acc):
        cookies = json.loads(acc["cookies"])
        ua      = acc["user_agent"]
        result  = await youtube_subscribe(channel_url, cookies, ua)
        if result:
            await db_add_subscription(acc["id"], channel_url, period_label, unsub_date)
        else:
            await db_mark_dead(acc["id"])
        return result

    success_count, fail_count = await run_parallel_task(sub_task, accounts, MAX_BROWSERS)
    active_subs = await db_count("subscriptions", "status='active'")

    await db_add_task_history("subscribe", channel_url, count, success_count, fail_count)

    unsub_str = unsub_date.strftime("%d.%m.%Y") if unsub_date else "♾ Umrbod"
    await status_msg.edit_text(
        f"✅ <b>Obuna jarayoni yakunlandi!</b>\n\n"
        f"📺 Kanal: <a href='{channel_url}'>link</a>\n"
        f"⏱ Muddat: <b>{period_label}</b>\n"
        f"📅 Obunadan chiqish: <b>{unsub_str}</b>\n"
        f"{'─' * 28}\n"
        f"✅ Muvaffaqiyatli: <b>{success_count} ta</b>\n"
        f"❌ Xato / o'lik akkaunt: <b>{fail_count} ta</b>\n"
        f"{'─' * 28}\n"
        f"📊 Jami faol obunalar: <b>{active_subs} ta</b>\n"
        f"🕐 {now_str()}",
        parse_mode="HTML",
        reply_markup=BACK_MAIN_KB,
        disable_web_page_preview=True
    )


# ──────────── STATISTIKA ────────────
async def show_statistics(source) -> None:
    total_acc  = await db_count("accounts")
    active_acc = await db_count("accounts", "status='active'")
    dead_acc   = await db_count("accounts", "status IN ('dead','blocked')")
    total_like = await db_count("likes")
    active_sub = await db_count("subscriptions", "status='active'")
    upcoming   = await db_upcoming_unsubs()

    upcoming_text = ""
    if upcoming:
        upcoming_text = "\n\n📅 <b>7 kunda obunadan chiqadiganlar:</b>\n"
        for row in upcoming:
            date_str = row["unsub_date"][:10] if row["unsub_date"] else "—"
            email = row["email"]
            upcoming_text += f"  • <code>{email}</code> → {date_str}\n"

    text = (
        f"📊 <b>Bot Statistikasi</b>\n"
        f"{'─' * 32}\n\n"
        f"👥 <b>Akkauntlar:</b>\n"
        f"  📦 Jami:            <b>{total_acc} ta</b>\n"
        f"  ✅ Faol:             <b>{active_acc} ta</b>\n"
        f"  ❌ O'lik/Bloklangan: <b>{dead_acc} ta</b>\n\n"
        f"👍 <b>Jami bosilgan likelar:</b>   <b>{total_like} ta</b>\n\n"
        f"🔔 <b>Hozirda faol obunalar:</b>   <b>{active_sub} ta</b>"
        f"{upcoming_text}\n\n"
        f"🕐 <i>{now_str()}</i>"
    )

    if isinstance(source, CallbackQuery):
        await source.message.edit_text(text, parse_mode="HTML", reply_markup=BACK_MAIN_KB)
        await source.answer()
    else:
        await source.answer(text, parse_mode="HTML", reply_markup=BACK_MAIN_KB)


@router.callback_query(F.data == "statistics")
async def cb_statistics(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return
    await show_statistics(cb)


# ──────────── AKKAUNTLAR RO'YXATI ────────────
@router.callback_query(F.data == "list_accounts")
async def cb_list_accounts(cb: CallbackQuery, state: FSMContext):
    if not await admin_guard(cb, state):
        return

    accounts = await db_all_accounts()

    if not accounts:
        await cb.message.edit_text(
            "📋 Bazada hech qanday akkaunt yo'q.",
            reply_markup=BACK_MAIN_KB
        )
        await cb.answer()
        return

    sep = "═" * 70
    lines = [
        sep,
        "  YouTube Automation Bot — Akkauntlar Ro'yxati",
        f"  Eksport: {now_str()}  |  Jami: {len(accounts)} ta",
        sep,
        f"{'#':<4}  {'Email':<36}  {'Status':<10}  {'Cookie':<7}  {'Qoshilgan':<12}  {'Xato'}",
        "─" * 70,
    ]

    for idx, acc in enumerate(accounts, 1):
        cookie_ok  = "✅" if acc["cookies"] else "❌"
        added      = acc["added_date"][:10] if acc["added_date"] else "—"
        fail       = acc["fail_count"] if "fail_count" in acc.keys() else 0
        lines.append(
            f"{idx:<4}  {acc['email']:<36}  {acc['status']:<10}  {cookie_ok:<7}  {added:<12}  {fail}"
        )

    lines += [sep, f"Jami: {len(accounts)} ta akkaunt", sep]
    content = "\n".join(lines).encode("utf-8")

    await cb.message.answer_document(
        document=BufferedInputFile(
            file=content,
            filename=f"accounts_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        ),
        caption=f"📋 <b>Akkauntlar ro'yxati</b>\nJami: <b>{len(accounts)} ta</b>",
        parse_mode="HTML",
        reply_markup=BACK_MAIN_KB
    )
    await cb.answer()


# ─────────────────────────────────────────────────────────────────────────────
#  CRON JOB — Obunani avtomatik bekor qilish
# ─────────────────────────────────────────────────────────────────────────────
async def check_and_unsubscribe() -> None:
    """
    Har soatda ishga tushadi.
    Muddati o'tgan obunalarni avtomatik bekor qiladi.
    """
    expired = await db_get_expired_subs()
    if not expired:
        logger.debug("✅ Cron: bekor qilinadigan obuna yo'q.")
        return

    logger.info(f"🔄 Cron: {len(expired)} ta muddati o'tgan obuna topildi.")

    for row in expired:
        try:
            cookies    = json.loads(row["cookies"])
            user_agent = row["user_agent"]
            result     = await youtube_unsubscribe(row["channel_url"], cookies, user_agent)
            if result:
                await db_cancel_sub(row["id"])
                logger.info(f"✅ Cron: obuna bekor → {row['email']} | {row['channel_url']}")
            else:
                logger.warning(f"⚠️ Cron: obuna bekor qilishda xato → {row['email']}")
        except Exception as e:
            logger.error(f"❌ Cron xato: {e}", exc_info=True)


# ─────────────────────────────────────────────────────────────────────────────
#  BOTNI ISHGA TUSHIRISH
# ─────────────────────────────────────────────────────────────────────────────
async def main() -> None:
    # Konfiguratsiya tekshiruvi
    if BOT_TOKEN == "YOUR_BOT_TOKEN_HERE":
        logger.critical("❌ BOT_TOKEN o'rnatilmagan! .env faylini tekshiring.")
        sys.exit(1)

    if ADMIN_ID == 123456789:
        logger.warning("⚠️ ADMIN_ID hali o'zgartirilmagan. .env faylini yangilang.")

    # DB
    await init_db()

    # Bot va Dispatcher
    from aiogram.client.default import DefaultBotProperties
    bot     = Bot(token=BOT_TOKEN, default=DefaultBotProperties(parse_mode="HTML"))
    storage = MemoryStorage()
    dp      = Dispatcher(storage=storage)
    dp.include_router(router)

    # Scheduler
    scheduler = AsyncIOScheduler(timezone="Asia/Tashkent")
    scheduler.add_job(
        check_and_unsubscribe,
        trigger="interval",
        hours=1,
        id="auto_unsub",
        max_instances=1,
        coalesce=True,
    )
    scheduler.start()
    logger.info("✅ Scheduler ishga tushdi — har 1 soatda obunalar tekshiriladi.")

    # Bot info
    me = await bot.get_me()
    logger.info(f"🤖 Bot ishga tushdi: @{me.username} | Admin: {ADMIN_ID} | Headless: {HEADLESS}")

    try:
        await dp.start_polling(
            bot,
            allowed_updates=dp.resolve_used_update_types(),
            drop_pending_updates=True,
        )
    finally:
        scheduler.shutdown(wait=False)
        await bot.session.close()
        logger.info("🛑 Bot to'xtatildi.")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("👋 Bot to'xtatildi (Ctrl+C).")