from scrapling.engines._browsers._stealth import StealthySession
from scrapling.parser import Adaptor
import json, os, urllib.request

url = 'https://www.instagram.com/avatarhype_br/reel/DcThzG6MvWS/'
cookies_path = '/opt/scrapling-runner/cookies/instagram.json'
cookies = []
if os.path.exists(cookies_path):
    with open(cookies_path) as f:
        cookies = json.load(f)

# O Scrapling StealthySession precisa ser usado como Context Manager (with)
with StealthySession(headless=True) as session:
    print(f'[*] Carregando sessão stealth com {len(cookies)} cookies...')
    res = session.fetch(url, cookies=cookies)
    print('Status:', res.status)
    tree = Adaptor(res.body)
    imgs = tree.css('img::attr(src)').getall()
    videos = tree.css('video::attr(src)').getall()
    print('Imagens encontradas no DOM renderizado:', len(imgs))
    print('Videos encontrados no DOM renderizado:', len(videos))
    
    job_dir = '/tmp/scrapling-jobs/job_avatarhype_live'
    os.makedirs(f'{job_dir}/frames', exist_ok=True)
    
    count = 0
    for src in imgs:
        if 'profile' not in src and 'scontent' in src:
            count += 1
            dest = f'{job_dir}/frame_{count:03d}.jpg'
            urllib.request.urlretrieve(src, dest)
            print(f'[+] Salvo frame JPG na VPS: {dest} ({os.path.getsize(dest)} bytes)')
            if count >= 10:
                break
    
    print(f'[+] TOTAL DE FRAMES BAIXADOS NA VPS: {count}')
