from __future__ import annotations

import logging
from playwright.sync_api import sync_playwright, Page

from loki.common.profile import Profile, ProfileManager
from loki.scrapers.base import RequestMixin

logger = logging.getLogger('loki')

class TikTok(RequestMixin):
    PLATFORM = "TikTok"
    
    def __init__(
        self,
        *,
        profile: Profile | None = None,
        profile_name: str = "default",
        profile_manager: ProfileManager | None = None,
        auto_load_cookies: bool = True,
    ) -> None:
        if profile is None:
            manager = profile_manager or ProfileManager()
            profile = manager.get(self.PLATFORM, profile_name)

        super().__init__(profile=profile, auto_load_cookies=auto_load_cookies)
        self._base = 'https://www.tiktok.com'
        self._playwright = sync_playwright().start()
        self._browser = self._playwright.chromium.launch(
            headless=False,
            args=[
                "--disable-blink-features=AutomationControlled",
            ]
        )
        
    def close(self) -> None:
        try:
            if getattr(self, "_browser", None):
                self._browser.close()
        finally:
            if getattr(self, "_playwright", None):
                self._playwright.stop()
                
    def _new_page(self) -> tuple[BrowserContext, Page] | tuple[None, None]:
        context = None
        try:
            context = self._browser.new_context(
                viewport={"width": 1280, "height": 800},
                user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36",
                locale="zh-CN",
                timezone_id="Asia/Shanghai",
            )
            page = context.new_page()
            return context, page
        except Exception:
            logger.exception("创建页面失败")
            if context:
                context.close()
            return None, None
     
    def get_profile_data(self, username: str) -> dict | None:
        profile_url = f"{self._base}/@{username}"

        context, page = self._new_page()
        if not page:
            return None

        try:
            with page.expect_response(
                lambda r: ("api/post/item_list" in r.url)
                          and r.request.resource_type in ("xhr", "fetch")
                          and r.status == 200,
                timeout=30000
            ) as resp_info:
                page.goto(profile_url, wait_until="domcontentloaded", timeout=30000)

            data = resp_info.value.json()
            return data

        except Exception:
            logger.exception("抓取 profile 接口失败: %s", profile_url)
            return None
        finally:
            context.close()