import pathlib
import pexpect
import shlex


password = pathlib.Path("/home/aaron/.secrets/beget-sftp-password.txt").read_text().strip()
php = r"""
$fields = get_fields(60);
$lines = 0;
$walk = function ($value, $path, $depth) use (&$walk, &$lines) {
    if ($lines >= 220 || $depth > 8) {
        return;
    }
    if (is_array($value)) {
        echo "ARRAY " . $path . " keys=" . implode(",", array_slice(array_keys($value), 0, 25)) . "\n";
        $lines++;
        foreach ($value as $key => $child) {
            $walk($child, $path . "/" . $key, $depth + 1);
            if ($lines >= 220) {
                break;
            }
        }
    } elseif (
        is_scalar($value)
        && preg_match("/(price|cost|title|name|route|car|vehicle|taxi|transfer|place|from|to|table|list|desc)/i", $path)
    ) {
        $text = trim(wp_strip_all_tags((string) $value));
        if ($text !== "") {
            echo "VALUE " . $path . "=" . mb_substr(preg_replace("/\s+/u", " ", $text), 0, 180) . "\n";
            $lines++;
        }
    }
};
foreach (["transfers", "pricelist"] as $root) {
    $walk($fields[$root] ?? [], $root, 0);
}
"""

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=90)
match = child.expect(["[Pp]assword:", pexpect.EOF, pexpect.TIMEOUT])
if match == 0:
    child.sendline(password)
    child.expect(pexpect.EOF)
print(child.before)
