import json
from playwright.sync_api import sync_playwright

class SnapchatClient:
    def __init__(self, headless=True):
        self.headless = headless

    def _get_page_data(self, username):
        """Scrapes the Next.js __NEXT_DATA__ block from Snapchat web."""
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=self.headless)
            # Use a typical user agent
            context = browser.new_context(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
            page = context.new_page()
            page.goto(f"https://www.snapchat.com/add/{username}")
            page.wait_for_load_state("domcontentloaded")
            
            # The page uses a __NEXT_DATA__ script block to inject props
            next_data = page.evaluate("() => { const el = document.getElementById('__NEXT_DATA__'); return el ? el.innerText : null; }")
            browser.close()
            
            if next_data:
                return json.loads(next_data)
            return None

    def get_profile(self, username):
        """Returns the public user profile info."""
        data = self._get_page_data(username)
        if not data:
            return None
        
        user_profile = data.get('props', {}).get('pageProps', {}).get('userProfile', {})
        case = user_profile.get('$case')
        if case == 'publicProfileInfo':
            return user_profile.get('publicProfileInfo', {})
        elif case == 'userInfo':
            return user_profile.get('userInfo', {})
        
        # Fallback
        return user_profile.get('publicProfileInfo') or user_profile.get('userInfo') or {}

    def get_stories(self, username):
        """Returns current public stories of the user."""
        data = self._get_page_data(username)
        if not data:
            return None
        story = data.get('props', {}).get('pageProps', {}).get('story', {})
        return story

    def get_highlights(self, username):
        """Returns curated and spotlight highlights of the user."""
        data = self._get_page_data(username)
        if not data:
            return None
        page_props = data.get('props', {}).get('pageProps', {})
        return {
            'curatedHighlights': page_props.get('curatedHighlights', []),
            'spotlightHighlights': page_props.get('spotlightHighlights', [])
        }

    def get_full_data(self, username):
        """Returns all aggregated data for a user."""
        data = self._get_page_data(username)
        if not data:
            return None
        page_props = data.get('props', {}).get('pageProps', {})
        user_profile = page_props.get('userProfile', {})
        case = user_profile.get('$case')
        profile_data = user_profile.get(case, {}) if case else (user_profile.get('publicProfileInfo') or user_profile.get('userInfo') or {})
        
        return {
            'profile': profile_data,
            'story': page_props.get('story', {}),
            'curatedHighlights': page_props.get('curatedHighlights', []),
            'spotlightHighlights': page_props.get('spotlightHighlights', [])
        }

if __name__ == "__main__":
    client = SnapchatClient()
    username = "kyliejenner"
    print(f"Fetching data for {username}...")
    full_data = client.get_full_data(username)
    if full_data:
        print(f"Profile: {full_data['profile'].get('displayName')} (@{full_data['profile'].get('username')})")
        print(f"Active Story Snaps: {len(full_data['story'].get('snapList', [])) if full_data['story'] else 0}")
        print(f"Curated Highlights: {len(full_data['curatedHighlights'])}")
        print(f"Spotlight Highlights: {len(full_data['spotlightHighlights'])}")
    else:
        print("Failed to fetch data.")
