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

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


class LinkedIn:
    RATE_LIMIT = 10
    _last_request = 0

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

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

    def _validate_linkedin_content(self, html: str) -> bool:
        """Check if we got real LinkedIn content."""
        if not html:
            return False
        
        indicators = [
            'linkedin.com',
            'class="profile',
            'data-member-id',
            'experience-item',
            'pv-profile',
            'org-company-employees-snackbar'
        ]
        
        return any(indicator in html for indicator in indicators)

    def profile(self, username, country="US", extract=False):
        """Fetch LinkedIn profile page with validation."""
        self._rate_limit()
        url = f"https://www.linkedin.com/in/{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_linkedin_content(resp.text):
                # Basic extraction from meta tags
                name_match = re.search(r'<title>([^<]*) \| LinkedIn</title>', resp.text)
                result["name"] = name_match.group(1).strip() if name_match else ""
                
                # Extract from meta description
                desc_match = re.search(r'<meta name="description" content="([^"]*)"', resp.text)
                result["description"] = desc_match.group(1) if desc_match else ""
            else:
                logger.warning("LinkedIn profile validation failed")
        
        return result

    def company(self, name, country="US", extract=False):
        """Fetch LinkedIn company page with validation."""
        self._rate_limit()
        url = f"https://www.linkedin.com/company/{name}/"
        
        resp = self.client.fetch(url, country=country)
        
        result = {
            "company": name,
            "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_linkedin_content(resp.text):
                # Extract company name
                company_match = re.search(r'<h1[^>]*>([^<]*)</h1>', resp.text)
                result["company_name"] = company_match.group(1).strip() if company_match else ""
                
                # Extract from meta description
                desc_match = re.search(r'<meta name="description" content="([^"]*)"', resp.text)
                result["description"] = desc_match.group(1) if desc_match else ""
        
        return result

    def search(self, query, country="US"):
        """Search LinkedIn."""
        self._rate_limit()
        import urllib.parse
        encoded_query = urllib.parse.quote_plus(query)
        url = f"https://www.linkedin.com/search/results/all/?keywords={encoded_query}"
        
        resp = self.client.fetch(url, country=country)
        
        return {
            "query": query,
            "url": url,
            "status": resp.status_code,
            "html": resp.text
        }
