#!/usr/bin/env python3
"""
Step 1: Login to Hotmart SSO, wait for 2FA, save browser state.
Step 2 will be called with OTP code to complete.
"""
import time
import sys
import re
from playwright.sync_api import sync_playwright

EMAIL = "mindreview.ia@gmail.com"
PASSWORD = "UNicamp@459917"
PRODUCT_ID = "4552866"
OFFER_NAME = "Acesso Zory"
STATE_FILE = '/home/zory/tmp/hotmart_state.json'
SS = '/home/zory/tmp/hotmart'

def step1_login():
    """Login and save state at 2FA page."""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, args=[
            '--no-sandbox', '--disable-dev-shm-usage',
            '--disable-blink-features=AutomationControlled'
        ])
        context = browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            locale='pt-BR',
            user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
        )
        context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        page = context.new_page()

        print("[1] Loading Hotmart SSO...")
        page.goto('https://sso.hotmart.com/login', wait_until='domcontentloaded', timeout=60000)
        page.wait_for_selector('input:visible', timeout=60000)
        time.sleep(2)

        print("[2] Filling credentials...")
        page.locator('#username').fill(EMAIL)
        page.locator('#password').fill(PASSWORD)

        print("[3] Submitting...")
        page.locator('button:has-text("Entrar")').click()
        time.sleep(6)

        body = page.inner_text('body')
        if 'verificação' in body.lower() or 'código' in body.lower():
            print("[4] 2FA page detected. Saving browser state...")
            context.storage_state(path=STATE_FILE)
            page.screenshot(path=f'{SS}_2fa.png')
            print(f"    State saved to {STATE_FILE}")
            print("    NEED OTP CODE from mindreview.ia@gmail.com")
        else:
            print(f"[4] No 2FA! URL: {page.url}")
            context.storage_state(path=STATE_FILE)

        browser.close()


def step2_otp_and_create(otp_code):
    """Resume with OTP, complete login, create offer."""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, args=[
            '--no-sandbox', '--disable-dev-shm-usage',
            '--disable-blink-features=AutomationControlled'
        ])
        context = browser.new_context(
            storage_state=STATE_FILE,
            viewport={'width': 1920, 'height': 1080},
            locale='pt-BR',
            user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
        )
        context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        page = context.new_page()

        # Capture API responses
        captured = []
        def on_resp(resp):
            u = resp.url.lower()
            if any(k in u for k in ['offer', 'checkout', 'payment']):
                try: body = resp.text()
                except: body = ''
                captured.append({'url': resp.url, 'status': resp.status, 'body': body[:3000]})
        page.on('response', on_resp)

        # Go back to login page where 2FA form is
        print(f"[1] Resuming with OTP: {otp_code}")
        page.goto('https://sso.hotmart.com/login', wait_until='domcontentloaded', timeout=60000)
        time.sleep(5)
        page.screenshot(path=f'{SS}_resume.png')
        body = page.inner_text('body')
        print(f"    Page: {body[:200]}")

        # Check if we're on 2FA or need to re-login
        if 'verificação' in body.lower() or 'código' in body.lower():
            print("[2] Filling OTP...")
            # Find the OTP input
            vis = page.locator('input:visible')
            c = vis.count()
            print(f"    Visible inputs: {c}")
            for i in range(c):
                html = vis.nth(i).evaluate('e => e.outerHTML')
                print(f"    [{i}] {html[:150]}")

            otp_filled = False
            for sel in [
                'input[type="text"]:visible', 'input[type="number"]:visible',
                'input[name*="code"]', 'input[name*="otp"]', 'input[name*="token"]',
                'input[maxlength="6"]',
            ]:
                try:
                    el = page.locator(sel).first
                    if el.is_visible(timeout=3000):
                        el.fill(otp_code)
                        otp_filled = True
                        print(f"    OTP filled via: {sel}")
                        break
                except:
                    continue

            if not otp_filled and c > 0:
                vis.first.fill(otp_code)
                print("    OTP in first visible input")

            page.screenshot(path=f'{SS}_otp_filled.png')

            # Click verify
            for sel in [
                'button:has-text("Verificar")', 'button:has-text("Verify")',
                'button:has-text("Confirmar")', 'button[type="submit"]',
            ]:
                try:
                    el = page.locator(sel).first
                    if el.is_visible(timeout=2000):
                        el.click()
                        print(f"    Clicked: {sel}")
                        break
                except:
                    continue

            # Wait for redirect
            print("[3] Waiting for auth...")
            try:
                page.wait_for_url(lambda u: 'dashboard' in u or 'tools' in u or 'app-vlc' in u, timeout=30000)
            except:
                time.sleep(10)
            print(f"    URL: {page.url}")
            page.screenshot(path=f'{SS}_post_otp.png')

        elif 'email' in body.lower() and 'senha' in body.lower():
            # Need to re-login, 2FA session expired
            print("[2] Session expired, re-logging in...")
            page.locator('#username').fill(EMAIL)
            page.locator('#password').fill(PASSWORD)
            page.locator('button:has-text("Entrar")').click()
            time.sleep(6)
            body2 = page.inner_text('body')
            if 'verificação' in body2.lower():
                print("    New 2FA requested! Need new code.")
                page.screenshot(path=f'{SS}_new_2fa.png')
                browser.close()
                return
        else:
            print(f"[2] Already logged in or unknown state: {page.url}")

        # ─── OFFERS PAGE ───
        print(f"\n[4] Going to product {PRODUCT_ID} offers...")
        page.goto(f'https://app-vlc.hotmart.com/tools/{PRODUCT_ID}/offers', wait_until='domcontentloaded', timeout=60000)
        time.sleep(8)
        page.screenshot(path=f'{SS}_offers.png')
        print(f"    URL: {page.url}")
        body = page.inner_text('body')
        print(f"    Page: {body[:400]}")

        if 'não encontrada' in body:
            # Try clicking "Ferramentas" in sidebar
            print("    Page not found, trying sidebar nav...")
            page.goto('https://app-vlc.hotmart.com/dashboard', wait_until='domcontentloaded', timeout=60000)
            time.sleep(5)
            page.screenshot(path=f'{SS}_dashboard.png')
            print(f"    Dashboard URL: {page.url}")
            # Navigate to product
            page.goto(f'https://app-vlc.hotmart.com/tools/{PRODUCT_ID}', wait_until='domcontentloaded', timeout=60000)
            time.sleep(5)
            page.screenshot(path=f'{SS}_product.png')
            print(f"    Product URL: {page.url}")
            body = page.inner_text('body')
            print(f"    Product page: {body[:300]}")

            # Try offers tab
            for sel in ['a:has-text("Ofertas")', 'a:has-text("Offers")', '[href*="offers"]']:
                try:
                    el = page.locator(sel).first
                    if el.is_visible(timeout=3000):
                        el.click()
                        time.sleep(3)
                        print(f"    Clicked offers tab: {sel}")
                        break
                except:
                    continue

            page.screenshot(path=f'{SS}_offers2.png')

        # ─── CREATE OFFER ───
        print("\n[5] Create offer...")
        create_found = False
        for sel in [
            'button:has-text("Criar oferta")', 'button:has-text("Nova oferta")',
            'a:has-text("Criar oferta")', 'a:has-text("Nova oferta")',
            'button:has-text("Create")', 'button:has-text("Adicionar")',
        ]:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    el.click()
                    create_found = True
                    print(f"    Clicked: {sel}")
                    break
            except:
                continue

        if not create_found:
            page.goto(f'https://app-vlc.hotmart.com/tools/{PRODUCT_ID}/offers/create', wait_until='domcontentloaded', timeout=60000)
            time.sleep(5)

        time.sleep(3)
        page.screenshot(path=f'{SS}_create.png')
        body = page.inner_text('body')
        print(f"    Create form: {body[:500]}")

        # List form elements
        vis = page.locator('input:visible, select:visible, textarea:visible')
        c = vis.count()
        print(f"    Form elements: {c}")
        for i in range(min(c, 15)):
            html = vis.nth(i).evaluate('e => e.outerHTML')
            print(f"    [{i}] {html[:150]}")

        # Fill name
        print("\n[6] Fill offer form...")
        for sel in ['input[name="name"]', 'input[name="offerName"]', 'input[placeholder*="nome" i]', 'input[type="text"]:visible']:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    el.fill(OFFER_NAME)
                    print(f"    Name: {sel}")
                    break
            except:
                continue

        # Free/price=0
        for sel in ['label:has-text("Gratuito")', 'span:has-text("Gratuito")']:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    el.click()
                    print(f"    Free: {sel}")
                    break
            except:
                continue

        for sel in ['input[name="price"]', 'input[name*="price"]', 'input[type="number"]:visible']:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    el.fill('0')
                    print(f"    Price=0: {sel}")
                    break
            except:
                continue

        page.screenshot(path=f'{SS}_filled.png')

        # Submit
        print("\n[7] Save...")
        for sel in ['button:has-text("Salvar")', 'button:has-text("Criar")', 'button:has-text("Save")', 'button[type="submit"]']:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    el.click()
                    print(f"    Submit: {sel}")
                    break
            except:
                continue

        time.sleep(5)
        page.screenshot(path=f'{SS}_saved.png')

        # ─── CHECKOUT CODE ───
        print("\n[8] Checkout code...")
        html = page.content()
        body = page.inner_text('body')
        print(f"    Body: {body[:300]}")

        for pat in [r'pay\.hotmart\.com/([A-Za-z0-9]+)', r'[Cc]ódigo[:\s]+([A-Z0-9]+)']:
            for src in [body, html]:
                m = re.search(pat, src, re.IGNORECASE)
                if m:
                    print(f"\n    ✓ CHECKOUT CODE: {m.group(1)}")

        for el in page.locator('a[href*="pay.hotmart"]').all():
            print(f"    Pay link: {el.get_attribute('href')}")

        if captured:
            print("\n[API]:")
            for r in captured[:10]:
                print(f"    {r['status']} {r['url'][:120]}")

        print(f"\n[DONE] {page.url}")
        page.screenshot(path=f'{SS}_final.png')
        browser.close()


if __name__ == '__main__':
    if len(sys.argv) > 1:
        step2_otp_and_create(sys.argv[1])
    else:
        step1_login()
