// Twitter/X session bootstrap for the setup flow.
//
// Thin wrapper over scripts/setup_twitter_auth.py, which owns the real work
// (ensure the managed Chrome on CDP 9555, validate the x.com session, and, if
// logged out, import x.com/twitter.com cookies from the user's everyday
// browser via ai_browser_profile.cookies). We only shell out and parse JSON.
//
// Why a separate Python helper instead of doing CDP here: the validation +
// cookie-import primitives already exist and are battle-tested in the repo
// (restore_twitter_session.py for CDP login-check, ai_browser_profile.cookies
// for Keychain-decrypt + CDP inject). Reusing them keeps this MCP a thin client.
import { runPython } from "./repo.js";
import { captureError } from "./telemetry.js";
function parse(stdout, stderr, code) {
    try {
        return JSON.parse(stdout.trim().split("\n").slice(-50).join("\n"));
    }
    catch {
        return {
            ok: false,
            connected: false,
            state: "error",
            error: `setup_twitter_auth.py produced no parseable JSON (exit ${code}).\n` +
                (stderr || stdout).split("\n").slice(-8).join("\n"),
        };
    }
}
// Probe-only: is the managed X session valid right now? Does NOT launch Chrome.
export async function xStatus() {
    const res = await runPython("scripts/setup_twitter_auth.py", ["status"], {
        timeoutMs: 90_000,
    });
    return parse(res.stdout, res.stderr, res.code);
}
// Ensure the browser is up, validate, and import cookies from the user's
// everyday browser if needed. `source` optional (e.g. "arc:Default"); default
// auto-detects chrome/arc/brave/edge.
export async function xConnect(source, manualLogin) {
    const args = ["connect"];
    if (source)
        args.push("--source", source);
    // Only pop a Chrome login window when the user explicitly asked to sign in by
    // hand. Without this, auto-import failures (no X session in the browser, etc.)
    // return needs_login WITHOUT shoving an unexpected browser window in front of
    // the user; the login window still opens on its own if they DENIED keychain.
    if (manualLogin)
        args.push("--manual-login");
    const res = await runPython("scripts/setup_twitter_auth.py", args, {
        // import opens a real Chrome and may pop a macOS Keychain auth dialog the
        // user has to find + click ("Always Allow"). Keep this above the Python
        // cookie-copy timeout (S4L_COOKIE_COPY_TIMEOUT, default 600s) so the
        // wrapper never kills the dialog before the human can.
        timeoutMs: 660_000,
    });
    return parse(res.stdout, res.stderr, res.code);
}
export async function xScanProfile(opts) {
    const args = [];
    if (opts?.handle)
        args.push("--handle", opts.handle);
    args.push("--posts", String(opts?.posts ?? 20));
    args.push("--comments", String(opts?.comments ?? 50));
    // The scan scrolls two timelines plus visits the top posts' permalinks for
    // thread expansion; give it room but keep it bounded.
    const res = await runPython("scripts/scan_x_profile.py", args, { timeoutMs: 240_000 });
    try {
        return JSON.parse(res.stdout.trim().split("\n").slice(-1).join("\n"));
    }
    catch (e) {
        // The X profile scan feeds handle detection + grounding for the draft lane; a
        // silent no-JSON failure here means we scrape the wrong handle (or none) and
        // never know. Surface it so we can see fleet-wide how often the scan breaks.
        captureError(e, {
            component: "twitter_auth",
            phase: "scan_x_profile",
            exit: String(res.code),
        });
        return {
            ok: false,
            state: "error",
            error: `scan_x_profile.py produced no parseable JSON (exit ${res.code}).\n` +
                (res.stderr || res.stdout).split("\n").slice(-8).join("\n"),
        };
    }
}
// List browsers/profiles to import from. Read-only: NEVER reads the keychain or
// decrypts a cookie, so it shows no macOS Safe Storage prompt. Used to populate
// the panel's "import from" dropdown and to flag which profile has a live session.
export async function xDetectSources() {
    const res = await runPython("scripts/setup_twitter_auth.py", ["detect-sources"], {
        timeoutMs: 30_000,
    });
    try {
        return JSON.parse(res.stdout.trim().split("\n").slice(-200).join("\n"));
    }
    catch (e) {
        // detect-sources populates the panel's "import from" dropdown; a no-JSON failure
        // leaves the user unable to connect X during setup with no server-side trace.
        captureError(e, {
            component: "twitter_auth",
            phase: "detect_sources",
            exit: String(res.code),
        });
        return {
            ok: false,
            sources: [],
            error: `detect-sources produced no parseable JSON (exit ${res.code}).\n` +
                (res.stderr || res.stdout).split("\n").slice(-8).join("\n"),
        };
    }
}
// One-line human summary for tool output.
export function summarizeXAuth(r) {
    switch (r.state) {
        case "connected":
            return "X is connected (the autoposter browser has a valid x.com session).";
        case "connected_idle":
            return ("X is connected (your session is saved). The autoposter's browser isn't " +
                "running this moment; the next cycle restores it from the local mirror " +
                "automatically — no action needed.");
        case "imported":
            return `X connected — imported your session from ${r.source ?? "your browser"}.`;
        case "logged_out":
            return "X is not connected: the autoposter browser has no valid x.com session yet.";
        case "browser_not_running":
            return "The autoposter's X browser isn't running yet.";
        case "needs_login":
            // Prefer the helper's note: it says whether the login window actually
            // came to the front and carries the full manual-login instructions.
            return (r.note ??
                "Couldn't import a valid X session automatically. A Chrome window is open at " +
                    "the X login page — sign in there yourself (username, password, 2FA), then " +
                    "run connect_x again to confirm.");
        case "browser_launch_failed":
            return r.error ?? "Could not start the autoposter browser.";
        default:
            return r.error ?? `X auth state: ${r.state}`;
    }
}
