"""TikTok site preset with validation."""
import time
import random
import re
import logging

logger = logging.getLogger("iploop.sites.tiktok")


class TikTok:
    RATE_LIMIT = 5
    _last_request = 0

    def __init__(self, client):
        self.client = client

    def _rate_limit(self):
        elapsed = time.time() - TikTok._last_request
        if elapsed < self.RATE_LIMIT:
            time.sleep(self.RATE_LIMIT - elapsed + random.uniform(0, 2))
        TikTok._last_request = time.time()

    def _extract_text(self, html: str) -> str:
        """Strip HTML tags and return clean text."""
        # Remove HTML tags
        text = re.sub(r'<[^>]+>', '', html)
        # Clean up whitespace
        text = re.sub(r'\s+', ' ', text).strip()
        return text

    def _extract_tiktok_profile(self, html: str, username: str) -> dict:
        """Extract from meta tags: og:description has follower/like counts."""
        data = {"username": username}
        
        # Extract from og:description meta tag
        og_desc_match = re.search(r'<meta property="og:description" content="([^"]*)"', html)
        if og_desc_match:
            desc = og_desc_match.group(1)
            data['description'] = desc
            
            # Extract follower count
            followers_match = re.search(r'([\d,.]+[KMB]?)\s+Followers', desc, re.IGNORECASE)
            if followers_match:
                data['followers'] = followers_match.group(1)
            
            # Extract following count
            following_match = re.search(r'([\d,.]+[KMB]?)\s+Following', desc, re.IGNORECASE)
            if following_match:
                data['following'] = following_match.group(1)
            
            # Extract likes count
            likes_match = re.search(r'([\d,.]+[KMB]?)\s+Likes', desc, re.IGNORECASE)
            if likes_match:
                data['likes'] = likes_match.group(1)
        
        # Extract from og:title
        og_title_match = re.search(r'<meta property="og:title" content="([^"]*)"', html)
        if og_title_match:
            data['title'] = og_title_match.group(1)
        
        # Extract from regular title tag as fallback
        title_match = re.search(r'<title>([^<]*)</title>', html)
        if title_match and not og_title_match:
            data['title'] = self._extract_text(title_match.group(1))
        
        return data

    def _validate_tiktok_content(self, html: str) -> bool:
        """Check if we got real TikTok content."""
        if not html:
            return False
        
        indicators = [
            'tiktok-',
            'data-e2e=',
            '__DEFAULT_SCOPE__',
            'followers-count',
            'following-count',
            'likes-count'
        ]
        
        return any(indicator in html for indicator in indicators)

    def profile(self, username, country="US", extract=False):
        """Fetch TikTok profile with validation."""
        self._rate_limit()
        url = f"https://www.tiktok.com/@{username}"
        
        from ..fingerprint import chrome_fingerprint
        resp = self.client.fetch(url, country=country, headers=chrome_fingerprint(country))
        
        result = {
            "username": username,
            "url": url,
            "status": resp.status_code,
            "html": resp.text,
            "size_kb": len(resp.text) // 1024
        }
        
        if extract and resp.status_code == 200:
            if self._validate_tiktok_content(resp.text):
                result["data"] = self._extract_tiktok_profile(resp.text, username)
            else:
                result["data"] = {"username": username}
        
        return result

    def video(self, video_id, country="US", extract=False):
        """Fetch a TikTok video page with validation."""
        self._rate_limit()
        url = f"https://www.tiktok.com/@user/video/{video_id}"
        
        resp = self.client.fetch(url, country=country)
        
        result = {
            "video_id": video_id,
            "url": url,
            "status": resp.status_code,
            "html": resp.text,
            "size_kb": len(resp.text) // 1024
        }
        
        if extract and resp.status_code == 200:
            if self._validate_tiktok_content(resp.text):
                # Extract video title/description
                title_match = re.search(r'<title>([^<]*)</title>', resp.text)
                result["title"] = title_match.group(1).strip() if title_match else ""
        
        return result
