/**
 * API Probe - 独立探针，连接 CDP 获取 /api/me 真实字段名
 * Usage: node api_probe.js
 */
"use strict";

async function main() {
    console.log("[Probe] Checking CDP targets...");
    
    let targets;
    try {
        const res = await fetch("http://127.0.0.1:8888/json");
        targets = await res.json();
    } catch (e) {
        console.error("[Probe] Cannot connect to CDP port 8888:", e.message);
        process.exit(1);
    }

    if (!Array.isArray(targets) || targets.length === 0) {
        console.log("[Probe] CDP targets: EMPTY (Pi Desktop has no debug targets)");
        console.log("[Probe] Waiting for targets to appear (polling every 5s)...");
        
        // Poll until targets appear
        for (let attempt = 1; attempt <= 60; attempt++) {
            await new Promise(r => setTimeout(r, 5000));
            try {
                const res = await fetch("http://127.0.0.1:8888/json");
                targets = await res.json();
                if (Array.isArray(targets) && targets.length > 0) {
                    console.log(`[Probe] Targets appeared after ${attempt * 5}s!`);
                    break;
                }
            } catch (_) {}
            if (attempt % 6 === 0) console.log(`[Probe] Still waiting... (${attempt * 5}s elapsed)`);
        }
        
        if (!targets || targets.length === 0) {
            console.error("[Probe] Timed out after 5 minutes. No targets found.");
            process.exit(1);
        }
    }

    // Find remote webview target
    console.log(`[Probe] Found ${targets.length} target(s):`);
    targets.forEach((t, i) => console.log(`  [${i}] type=${t.type} title="${t.title}" url=${(t.url || "").substring(0, 80)}`));

    const remote = targets.find(t =>
        (t.url && t.url.includes("minepi.com") && t.type === "webview") ||
        (t.title === "Pi" && t.type === "webview")
    );

    if (!remote) {
        console.error("[Probe] No remote webview target found. Cannot fetch API data.");
        process.exit(1);
    }

    console.log(`[Probe] Connecting to remote: ${remote.webSocketDebuggerUrl}`);

    // Connect via WebSocket
    const ws = new WebSocket(remote.webSocketDebuggerUrl);
    let msgId = 0;
    const pending = new Map();

    function send(method, params = {}) {
        return new Promise((resolve, reject) => {
            const id = ++msgId;
            const timeout = setTimeout(() => { pending.delete(id); reject(new Error(`Timeout: ${method}`)); }, 15000);
            pending.set(id, (data) => { clearTimeout(timeout); pending.delete(id); if (data.error) reject(new Error(data.error.message)); else resolve(data.result); });
            ws.send(JSON.stringify({ id, method, params }));
        });
    }

    await new Promise((resolve, reject) => {
        ws.onopen = resolve;
        ws.onerror = reject;
        setTimeout(() => reject(new Error("WS connect timeout")), 10000);
    });

    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.id && pending.has(data.id)) pending.get(data.id)(data);
    };

    console.log("[Probe] Connected! Enabling Runtime...");
    await send("Runtime.enable");

    // Fetch /api/me via browser context
    const apiScript = `(async function() {
        try {
            var h = {};
            var t = localStorage.getItem('mobile-app-webview-ui_access-token');
            if(t) h['Authorization'] = 'Bearer ' + t;
            var me = await fetch('https://socialchain.app/api/me', {headers: h}).then(r => r.json());
            var st = await fetch('https://socialchain.app/api/mining_sessions/status', {headers: h}).then(r => r.json());
            return JSON.stringify({me: me, status: st, hasToken: !!t}, null, 2);
        } catch(e) { return JSON.stringify({error: e.message}); }
    })()`;

    console.log("[Probe] Fetching /api/me and /api/mining_sessions/status...");
    const result = await send("Runtime.evaluate", { expression: apiScript, awaitPromise: true, returnByValue: true });
    const value = result.result?.value;

    if (!value) {
        console.error("[Probe] No response from API call");
    } else {
        const parsed = JSON.parse(value);
        if (parsed.error) {
            console.error(`[Probe] API Error: ${parsed.error}`);
        } else {
            console.log("\n========== /api/me FULL RESPONSE ==========");
            console.log(JSON.stringify(parsed.me, null, 2));
            console.log("\n========== /api/me KEYS ==========");
            console.log(Object.keys(parsed.me || {}).join(", "));
            
            // Deep scan for username-like fields
            const me = parsed.me || {};
            console.log("\n========== USERNAME CANDIDATES ==========");
            const candidates = ["username", "display_name", "profile_name", "name", "uid", "user_name", "displayName", "profileName", "pi_username"];
            candidates.forEach(key => {
                if (me[key] !== undefined) console.log(`  ✅ me.${key} = "${me[key]}"`);
                else console.log(`  ❌ me.${key} = undefined`);
            });
            
            // Print any string values that might be usernames
            console.log("\n========== ALL STRING FIELDS ==========");
            for (const [k, v] of Object.entries(me)) {
                if (typeof v === "string") console.log(`  me.${k} = "${v}"`);
                else if (typeof v === "object" && v !== null) {
                    for (const [k2, v2] of Object.entries(v)) {
                        if (typeof v2 === "string") console.log(`  me.${k}.${k2} = "${v2}"`);
                    }
                }
            }

            console.log("\n========== /api/mining_sessions/status KEYS ==========");
            console.log(Object.keys(parsed.status || {}).join(", "));
            console.log("\n========== status.total_rate ==========");
            console.log(parsed.status?.total_rate);
            console.log("\n========== status.node ==========");
            console.log(JSON.stringify(parsed.status?.node, null, 2));
        }
    }

    ws.close();
    console.log("\n[Probe] Done.");
    process.exit(0);
}

main().catch(err => { console.error("[Probe] Fatal:", err.message); process.exit(1); });
