#!/usr/bin/env python3
"""
i21 Integration SQL execution via headless browser v3.
Fix: inject cookies with correct domain, use page.evaluate for login form submission.
"""
import subprocess, re, json, asyncio, time
from playwright.async_api import async_playwright

IP = "66.175.238.112"
APP = "2610RTROGERSUAP1"
BASE = f"http://{IP}/{APP}"

def curl_login(ip, app):
    subprocess.run(["curl","-sS","-m","15","-c","/tmp/pl1.txt","-o","/tmp/pp1.html",
                    f"http://{ip}/{app}/login"], capture_output=True, text=True, timeout=20)
    page = open("/tmp/pp1.html").read()
    tm = re.search(r'name="__RequestVerificationToken"[^>]*value="([^"]*)"', page)
    if not tm: return None, None
    token = tm.group(1)
    r2 = subprocess.run(["curl","-sS","-m","15","-c","/tmp/pl2.txt","-o","/dev/null","-w","%{http_code}",
                         "-b","/tmp/pl1.txt","-X","POST",f"http://{ip}/{app}/login",
                         "-H","Content-Type: application/x-www-form-urlencoded",
                         "-d",f"__RequestVerificationToken={token}&Email=irelyadmin&Password=i21By2015&Company=01&RememberMe=false&Concurrency=&CompanyPrefConcurrency=&UserPrefConcurrency=&Debug=False&Hash="],
                        capture_output=True, text=True, timeout=20)
    if r2.stdout.strip() != "302": return None, None
    
    cookies = []
    with open("/tmp/pl2.txt") as f:
        for line in f:
            if line.strip() and not line.startswith("#") and "\t" in line:
                parts = line.strip().split("\t")
                if len(parts) >= 7:
                    cookies.append({
                        "name": parts[5], "value": parts[6],
                        "path": parts[2] if len(parts) > 2 else "/",
                        "httpOnly": "#HttpOnly" in parts[0]
                    })
    return cookies, token

async def main():
    print("=== Login via curl ===")
    cookies, token = curl_login(IP, APP)
    if not cookies:
        print("Login failed"); return
    print(f"Got {len(cookies)} cookies:")
    for c in cookies:
        print(f"  {c['name']}: {c['value'][:50]}... path={c['path']}")

    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width":1920,"height":1080})
        
        # First navigate to the site to set the domain
        page = await context.new_page()
        await page.goto(f"{BASE}/login", wait_until="domcontentloaded", timeout=15000)
        
        # Now add cookies with the correct domain
        cookie_list = []
        for c in cookies:
            cookie_list.append({
                "name": c["name"],
                "value": c["value"],
                "domain": IP,
                "path": c["path"],
                "httpOnly": c.get("httpOnly", False),
                "secure": False
            })
        await context.add_cookies(cookie_list)
        print(f"\nInjected {len(cookie_list)} cookies")
        
        # Navigate to dashboard — should NOT redirect to login
        print("\n=== Navigate to dashboard ===")
        await page.goto(f"{BASE}/", wait_until="networkidle", timeout=30000)
        await asyncio.sleep(5)
        
        url = page.url
        print(f"  URL: {url}")
        
        if "login" in url.lower() or "Login" in url:
            print("  ❌ Still redirected to login")
            # Try: submit login form via JS (bypass reCAPTCHA by calling the form submit directly)
            print("  Trying JS form submission...")
            await page.fill('input[name="Email"]', 'irelyadmin')
            await page.fill('input[name="Password"]', 'i21By2015')
            
            # Set company
            await page.evaluate('''() => {
                const company = document.querySelector('input[name="Company"]');
                if (company) company.value = '01';
                const companyId = document.querySelector('#company-id');
                if (companyId) companyId.value = '';
            }''')
            
            # Submit form via JavaScript (not button click — bypasses reCAPTCHA)
            result = await page.evaluate('''() => {
                const form = document.querySelector('form');
                if (form) {
                    form.submit();
                    return 'form submitted';
                }
                return 'no form found';
            }''')
            print(f"  JS submit: {result}")
            await asyncio.sleep(5)
            await page.wait_for_load_state("networkidle", timeout=15000)
            print(f"  After JS submit URL: {page.url}")
        
        if "login" in page.url.lower():
            print("  ❌ Login still failed — trying direct cookie injection approach")
            # Last resort: use page.request (API) with cookies
            # Navigate with cookies set
            await page.goto(f"{BASE}/", wait_until="domcontentloaded", timeout=15000)
            # Force-set cookies via JS
            for c in cookies:
                await page.evaluate(f'''document.cookie = "{c['name']}={c['value']}; path={c['path']}"''')
            await page.reload(wait_until="networkidle", timeout=20000)
            await asyncio.sleep(3)
            print(f"  After cookie injection + reload: {page.url}")
        
        if "login" not in page.url.lower():
            print("  ✅ Dashboard loaded!")
            await page.screenshot(path="/tmp/dash.png")
            
            # Navigate to Integration
            print("\n=== Integration module ===")
            await page.goto(f"{BASE}/#Integration", wait_until="networkidle", timeout=20000)
            await asyncio.sleep(5)
            await page.screenshot(path="/tmp/integration.png")
            
            # Get all text content
            content = await page.content()
            print(f"  Page size: {len(content)}")
            
            # Find all menu items
            menu_items = await page.evaluate('''() => {
                const items = [];
                document.querySelectorAll('*').forEach(el => {
                    if (el.children.length === 0 && el.textContent) {
                        const t = el.textContent.trim();
                        if (t.length > 2 && t.length < 40) {
                            items.push({tag: el.tagName, text: t, id: el.id, cls: el.className.substring(0,40)});
                        }
                    }
                });
                return items;
            }''')
            
            # Filter for interesting items
            keywords = ["integration", "sql", "execute", "query", "database", "external",
                        "program", "process", "step", "connection", "import", "export",
                        "transform", "send", "file", "ftp", "schedule"]
            interesting = [m for m in menu_items if any(k in m["text"].lower() for k in keywords)]
            print(f"\n  Interesting menu items ({len(interesting)}):")
            for m in interesting[:20]:
                print(f"    {m['tag']}#{m['id']} '{m['text'][:40]}' cls={m['cls'][:30]}")
            
            # Try clicking Integration
            for item in menu_items:
                if item["text"].strip() == "Integration":
                    print(f"\n  Clicking Integration ({item['tag']}#{item['id']})")
                    el = await page.query_selector(f"#{item['id']}")
                    if el:
                        await el.click(timeout=5000)
                        await asyncio.sleep(3)
                        await page.screenshot(path="/tmp/integration_expanded.png")
                        
                        # Get new menu items
                        new_items = await page.evaluate('''() => {
                            const items = [];
                            document.querySelectorAll('*').forEach(el => {
                                if (el.children.length === 0 && el.textContent) {
                                    const t = el.textContent.trim();
                                    if (t.length > 2 && t.length < 40) items.push({tag: el.tagName, text: t, id: el.id});
                                }
                            });
                            return items;
                        }''')
                        new_interesting = [m for m in new_items if any(k in m["text"].lower() for k in keywords)]
                        print(f"  New items after click ({len(new_interesting)}):")
                        for m in new_interesting[:15]:
                            print(f"    {m['tag']}#{m['id']} '{m['text'][:40]}'")
                        break
            
            # AJAX log
            print(f"\n=== AJAX requests ===")
            # Re-capture from page
            ajax = await page.evaluate('''() => {
                // Can't access previous requests, but we can check performance entries
                return performance.getEntriesByType('resource').map(e => e.name.split(arguments[0])[1] || e.name).filter(n => n);
            }''')
        
        await browser.close()

asyncio.run(main())
