#!/usr/bin/env python3
"""Uji dugaan: script loader Trustindex (cdn.trustindex.io/loader.js) tertahan WP Rocket
sehingga widget ulasan tidak pernah dirender (opacity 0, tinggi 0) tapi tetap melebarkan halaman."""
from playwright.sync_api import sync_playwright

URL = "https://studiosoft.id/"
req_trust, errors, gagal = [], [], []

with sync_playwright() as p:
    b = p.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
    ctx = b.new_context(viewport={"width": 390, "height": 900}, is_mobile=True, has_touch=True)
    pg = ctx.new_page()
    pg.on("request", lambda r: req_trust.append(r.url) if "trustindex" in r.url else None)
    pg.on("requestfailed", lambda r: gagal.append((r.url[:90], r.failure)) if "trustindex" in r.url else None)
    pg.on("console", lambda m: errors.append(f"{m.type}: {m.text[:120]}") if m.type in ("error", "warning") else None)
    pg.goto(URL, wait_until="load", timeout=90000)
    pg.wait_for_timeout(8000)

    print("=== permintaan ke trustindex ===")
    for u in req_trust:
        print("   ", u[:110])
    if gagal:
        print("   GAGAL:", gagal)
    print("\n=== pesan konsol (error/warning) ===")
    for e in errors[:12]:
        print("   ", e)

    sebelum = pg.evaluate("""() => { const w=document.querySelector('.ti-widget'); const r=w.getBoundingClientRect();
        return {opacity:getComputedStyle(w).opacity, tinggi:Math.round(r.height), lebar:Math.round(r.width),
                scrollWidth:document.documentElement.scrollWidth}; }""")
    print("\n=== sebelum menyuntik loader ===")
    print("   ", sebelum)

    # suntikkan loader.js secara manual, seperti yang seharusnya dijalankan browser
    pg.evaluate("""() => new Promise(res => {
        const s = document.createElement('script');
        s.src = 'https://cdn.trustindex.io/loader.js';
        s.async = true; s.onload = () => res('ok'); s.onerror = () => res('gagal');
        document.head.appendChild(s);
        setTimeout(() => res('timeout'), 8000);
    })""")
    pg.wait_for_timeout(6000)
    sesudah = pg.evaluate("""() => { const w=document.querySelector('.ti-widget'); const r=w.getBoundingClientRect();
        const s=getComputedStyle(w);
        return {opacity:s.opacity, tinggi:Math.round(r.height), lebar:Math.round(r.width),
                gaya:w.getAttribute('style')||'(tanpa style)',
                scrollWidth:document.documentElement.scrollWidth, innerWidth:window.innerWidth,
                lebih:document.documentElement.scrollWidth-window.innerWidth}; }""")
    print("\n=== sesudah loader disuntik manual ===")
    for k, v in sesudah.items():
        print(f"   {k:<12}: {v}")
    pg.screenshot(path="ss_setelah_loader_disuntik.png")
    ctx.close()
    b.close()
print("\nscreenshot: ss_setelah_loader_disuntik.png")
