import asyncio
import json
import os
import time
import urllib.request
from patchright.async_api import async_playwright

async def run():
    url = 'https://www.instagram.com/p/DdB_VUJmCcN/'
    job_id = f'job_ddb_{int(time.time())}'
    tmp_dir = f'/tmp/scrapling-jobs/{job_id}'
    os.makedirs(f'{tmp_dir}/media', exist_ok=True)

    async with async_playwright() as p:
        browser = await p.chromium.launch(
            executable_path='/root/.cache/ms-playwright/chromium-1223/chrome-linux64/chrome',
            headless=True,
            args=['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-blink-features=AutomationControlled']
        )
        context = await browser.new_context(
            viewport={'width': 1280, 'height': 900},
            user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
        )
            
        page = await context.new_page()

        media_intercepted = []
        def handle_response(response):
            r_url = response.url
            ct = response.headers.get('content-type', '')
            if 'cdninstagram' in r_url or 'scontent' in r_url:
                if '.mp4' in r_url or 'video' in ct:
                    if r_url not in [m['url'] for m in media_intercepted]:
                        media_intercepted.append({'type': 'video', 'url': r_url})
                elif any(ext in r_url for ext in ['.jpg', '.jpeg', '.webp', '.png']) or 'image' in ct:
                    if 'scontent' in r_url and '150x150' not in r_url and 'profile' not in r_url:
                        if r_url not in [m['url'] for m in media_intercepted]:
                            media_intercepted.append({'type': 'image', 'url': r_url})

        page.on('response', handle_response)
        print('[*] Navegando...')
        await page.goto(url, wait_until='networkidle')
        await asyncio.sleep(5)

        title = await page.title()

        # Obter texto da legenda e autor
        author = ''
        caption_text = ''
        try:
            author_el = await page.query_selector('header a, a.xt0psk2, a[role=link] span')
            if author_el:
                author = await author_el.inner_text()
        except Exception:
            pass

        try:
            for sel in ['h1', 'div._a9zs', 'span._ap3a', 'article', 'div._aa-k']:
                elements = await page.query_selector_all(sel)
                for el in elements:
                    txt = await el.inner_text()
                    if len(txt) > len(caption_text):
                        caption_text = txt
        except Exception:
            pass

        # Percorrer carrossel usando evaluate no DOM para clicar no botão de avançar com segurança
        for step in range(15):
            clicked = await page.evaluate('''() => {
                const buttons = Array.from(document.querySelectorAll('button'));
                for (const b of buttons) {
                    const aria = (b.getAttribute('aria-label') || '').toLowerCase();
                    if (aria.includes('next') || aria.includes('avançar') || aria.includes('siguiente')) {
                        b.click();
                        return true;
                    }
                }
                const svgNext = document.querySelector('svg[aria-label=Avançar], svg[aria-label=Next], svg[aria-label=Siguiente]');
                if (svgNext && svgNext.closest('button')) {
                    svgNext.closest('button').click();
                    return true;
                }
                return false;
            }''')
            if clicked:
                print(f'[+] Avançou slide ({step+2})')
                await asyncio.sleep(2)
            else:
                break

        # Coletar imagens adicionais do DOM
        img_srcs = await page.evaluate('''() => {
            return Array.from(document.querySelectorAll('article img, div img'))
                .map(img => ({src: img.src, alt: img.alt || ''}))
                .filter(i => i.src && i.src.includes('scontent') && !i.src.includes('150x150'));
        }''')

        downloaded = []
        saved_urls = set()

        # Baixar imagens do DOM
        for item in img_srcs:
            src = item['src']
            if src in saved_urls:
                continue
            saved_urls.add(src)
            filename = f'slide_{len(downloaded)+1:02d}.jpg'
            dest = f'{tmp_dir}/media/{filename}'
            try:
                urllib.request.urlretrieve(src, dest)
                size = os.path.getsize(dest)
                if size > 15000:
                    downloaded.append({
                        'filename': filename,
                        'path': dest,
                        'size': size,
                        'alt': item.get('alt', ''),
                        'url': src,
                        'type': 'image'
                    })
                    print(f'[+] Imagem salva do DOM: {filename} ({size} bytes)')
            except Exception as e:
                pass

        # Baixar mídias interceptadas que não foram baixadas ainda
        for idx, m in enumerate(media_intercepted):
            m_url = m['url']
            if m_url in saved_urls:
                continue
            saved_urls.add(m_url)
            if m['type'] == 'image':
                filename = f'media_intercepted_{len(downloaded)+1:02d}.jpg'
            else:
                filename = f'media_intercepted_{len(downloaded)+1:02d}.mp4'
            dest = f'{tmp_dir}/media/{filename}'
            try:
                urllib.request.urlretrieve(m_url, dest)
                size = os.path.getsize(dest)
                if size > 15000:
                    downloaded.append({
                        'filename': filename,
                        'path': dest,
                        'size': size,
                        'url': m_url,
                        'type': m['type']
                    })
                    print(f'[+] Mídia interceptada salva: {filename} ({size} bytes)')
            except Exception as e:
                pass

        screenshot_path = f'{tmp_dir}/media/page_screenshot.png'
        await page.screenshot(path=screenshot_path, full_page=True)

        meta = {
            'job_id': job_id,
            'url': url,
            'author': author,
            'page_title': title,
            'caption': caption_text,
            'downloaded_media': downloaded
        }
        with open(f'{tmp_dir}/metadata.json', 'w', encoding='utf-8') as f:
            json.dump(meta, f, indent=2, ensure_ascii=False)

        print('===JOB_SUMMARY===')
        print(f'JOB_DIR:{tmp_dir}')
        print(f'MEDIA_COUNT:{len(downloaded)}')
        print(f'PAGE_TITLE:{title}')
        print(f'AUTHOR:{author}')
        print('===CAPTION_START===')
        print(caption_text)
        print('===CAPTION_END===')
        await browser.close()

asyncio.run(run())
