import pathlib
import pexpect
import shlex


password = pathlib.Path("/home/aaron/.secrets/beget-sftp-password.txt").read_text().strip()
php = r"""
$post_id = 2932;
$fields = get_fields($post_id) ?: [];
$result = [
    "post" => [
        "id" => $post_id,
        "type" => get_post_type($post_id),
        "title" => get_the_title($post_id),
        "field_keys" => array_keys($fields),
        "programs" => $fields["programs"] ?? null,
        "category_fields" => array_filter(
            $fields,
            static fn ($key) => preg_match("/cat|type|tag|filter|group/i", (string) $key),
            ARRAY_FILTER_USE_KEY
        ),
        "taxonomies" => [],
    ],
    "category_pages" => [],
];

foreach (get_object_taxonomies((string) get_post_type($post_id)) as $taxonomy) {
    $terms = wp_get_post_terms($post_id, $taxonomy, ["fields" => "all"]);
    $result["post"]["taxonomies"][$taxonomy] = is_wp_error($terms)
        ? []
        : array_map(
            static fn ($term) => [
                "id" => $term->term_id,
                "slug" => $term->slug,
                "name" => $term->name,
            ],
            $terms
        );
}

$pages = get_posts([
    "post_type" => "page",
    "post_status" => "publish",
    "posts_per_page" => -1,
    "meta_key" => "_wp_page_template",
    "meta_value" => "template-tourcat.php",
    "orderby" => "menu_order title",
    "order" => "ASC",
]);

$tour_types = ["pattaya", "phuket", "yacht", "yacht_phuket", "zoo_pattaya", "zoo_phuket"];
$collect_ids = function ($value) use (&$collect_ids, $tour_types): array {
    $ids = [];
    if ($value instanceof WP_Post) {
        if (in_array($value->post_type, $tour_types, true)) {
            $ids[] = $value->ID;
        }
        return $ids;
    }
    if (is_numeric($value)) {
        $type = get_post_type((int) $value);
        if (in_array($type, $tour_types, true)) {
            $ids[] = (int) $value;
        }
        return $ids;
    }
    if (!is_array($value)) {
        return $ids;
    }
    foreach ($value as $child) {
        $ids = array_merge($ids, $collect_ids($child));
    }
    return array_values(array_unique($ids));
};

foreach ($pages as $page) {
    $page_fields = get_fields($page->ID) ?: [];
    $tour_ids = $collect_ids($page_fields);
    $result["category_pages"][] = [
        "id" => $page->ID,
        "slug" => $page->post_name,
        "title" => get_the_title($page),
        "url" => get_permalink($page),
        "field_keys" => array_keys($page_fields),
        "tour_count" => count($tour_ids),
        "contains_2932" => in_array($post_id, $tour_ids, true),
        "sample_tour_ids" => array_slice($tour_ids, 0, 8),
    ];
}

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)
