<?php
/**
 * Tool: normalize_headings
 *
 * Rule for v1: theme renders the page title as <h1>, so all in-content
 * headings should be H2 (major sections) or H3 (subsections).
 *
 * Heuristic:
 *   - Walk the headings on the page in document order.
 *   - First heading at any level becomes the anchor: treat it as H2.
 *   - Subsequent headings at the same OR higher level (smaller number)
 *     in the source remain at H2.
 *   - Headings at strictly lower level (larger number) become H3.
 *   - H1 in content always becomes H2 (page title is already H1).
 *   - H4..H6 collapse to H3.
 *
 * Does not change heading text.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_normalize_headings($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);
    $changes = [];

    $first_level = null;
    $blocks = swcp_walk_blocks($blocks, function (&$b) use (&$first_level, &$changes) {
        if (!isset($b['blockName']) || $b['blockName'] !== 'core/heading') return null;
        $level = swcp_heading_level($b);
        if (!$level) return null;

        if ($first_level === null) {
            $first_level = $level;
        }

        // Whatever level the user used FIRST is the section anchor.
        // At-or-above that level becomes H2; anything below becomes H3.
        if ($level === 1) {
            $new_level = 2;
        } elseif ($level <= $first_level) {
            $new_level = 2;
        } else {
            $new_level = 3;
        }

        if ($new_level !== $level) {
            $changes[] = [
                'text' => swcp_block_text($b),
                'from' => 'H' . $level,
                'to'   => 'H' . $new_level,
            ];
            swcp_set_heading_level($b, $new_level);
        }
        return $b;
    });

    if (empty($changes)) {
        return [
            'ok'      => true,
            'message' => 'Heading levels on "' . esc_html(get_the_title($post)) . '" are already consistent. Nothing to change.',
            'page_id' => $post->ID,
        ];
    }

    $saved = swcp_save_blocks($post->ID, $blocks);
    if (!$saved) {
        return ['ok' => false, 'message' => 'Found inconsistent headings but failed to save the page.'];
    }

    $summary_lines = array_map(function ($c) {
        return $c['from'] . ' → ' . $c['to'] . ': "' . $c['text'] . '"';
    }, array_slice($changes, 0, 8));

    return [
        'ok'         => true,
        'message'    => 'Normalized ' . count($changes) . ' heading level(s) on "' . esc_html(get_the_title($post)) . '". ' . implode('; ', $summary_lines) . (count($changes) > 8 ? '; …' : ''),
        'page_id'    => $post->ID,
        'view_url'   => swcp_view_url_for($post->ID),
        'edit_url'   => swcp_edit_url_for($post->ID),
        'changes'    => $changes,
    ];
}
