<?php
/**
 * Tool: fix_duplicate_titles
 * Removes consecutive duplicate heading blocks (same text + level).
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_fix_duplicate_titles($input, $ctx) {
    $page_arg = isset($input['page']) ? $input['page'] : 'current';
    $resolved = swcp_resolve_or_error($page_arg, $ctx['post_id'] ?? 0);
    if (is_array($resolved) && isset($resolved['ok']) && !$resolved['ok']) return $resolved;
    $post = $resolved;

    $blocks  = swcp_get_blocks($post);
    $removed = [];
    $new     = [];
    $prev    = null;

    foreach ($blocks as $b) {
        $is_heading = isset($b['blockName']) && $b['blockName'] === 'core/heading';
        if ($is_heading && $prev) {
            $same_text  = strcasecmp(swcp_block_text($b), swcp_block_text($prev)) === 0;
            $same_level = swcp_heading_level($b) === swcp_heading_level($prev);
            if ($same_text && $same_level) {
                $removed[] = swcp_block_text($b);
                continue;
            }
        }
        $new[]  = $b;
        $prev   = $is_heading ? $b : $prev;
        // only "consecutive" duplicates — reset prev once we leave a heading
        if (!$is_heading) $prev = null;
    }

    if (empty($removed)) {
        return [
            'ok'      => true,
            'message' => 'No duplicate titles found on "' . esc_html(get_the_title($post)) . '". Nothing to fix.',
            'page_id' => $post->ID,
        ];
    }

    $saved = swcp_save_blocks($post->ID, $new);
    if (!$saved) {
        return ['ok' => false, 'message' => 'Found duplicates but failed to save the page. WP returned an error.'];
    }
    return [
        'ok'         => true,
        'message'    => 'Removed ' . count($removed) . ' duplicate title(s) on "' . esc_html(get_the_title($post)) . '": ' . implode(', ', array_map(function ($t) { return '"' . $t . '"'; }, $removed)),
        'page_id'    => $post->ID,
        'view_url'   => swcp_view_url_for($post->ID),
        'edit_url'   => swcp_edit_url_for($post->ID),
        'removed'    => $removed,
    ];
}
