import pathlib
import pexpect
import shlex


password = pathlib.Path("/home/aaron/.secrets/beget-sftp-password.txt").read_text().strip()
php = r"""
$summarize = function ($value, $depth = 0) use (&$summarize) {
    if ($value instanceof WP_Post) {
        return [
            "_post" => $value->ID,
            "type" => $value->post_type,
            "title" => get_the_title($value),
        ];
    }
    if (is_scalar($value) || $value === null) {
        return is_string($value) ? mb_substr(wp_strip_all_tags($value), 0, 220) : $value;
    }
    if (!is_array($value)) {
        return gettype($value);
    }
    $is_list = array_is_list($value);
    $out = ["_count" => count($value)];
    if ($depth >= 6) {
        return $out;
    }
    $limit = $is_list ? min(5, count($value)) : count($value);
    $index = 0;
    foreach ($value as $key => $child) {
        if ($index >= $limit) {
            break;
        }
        $out[(string) $key] = $summarize($child, $depth + 1);
        $index++;
    }
    return $out;
};

$result = [];
foreach ([299, 694] as $page_id) {
    $result[(string) $page_id] = [
        "title" => get_the_title($page_id),
        "block_6" => $summarize(get_field("block_6", $page_id)),
    ];
}
echo wp_json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
"""

remote = (
    "php8.2 /usr/local/bin/wp-cli.phar "
    "--path=/home/m/max9581h/max9581h.beget.tech/public_html "
    "eval "
    + shlex.quote(php)
    + " 2>/dev/null"
)
command = (
    "ssh -o StrictHostKeyChecking=accept-new "
    "max9581h_aaronseo@max9581h.beget.tech "
    + shlex.quote(remote)
)
child = pexpect.spawn("/bin/bash", ["-lc", command], encoding="utf-8", timeout=120)
match = child.expect(["[Pp]assword:", pexpect.EOF, pexpect.TIMEOUT])
if match == 0:
    child.sendline(password)
    child.expect(pexpect.EOF)
print(child.before)
