<?php
/**
 * Tool: iterate_page_design
 *
 * Cheap, fast refinement of an existing preview using Haiku 4.5 instead
 * of Opus 4.7. Use for "make it warmer", "less spacing", "swap the
 * accent colour", etc — anything that adjusts an existing design rather
 * than rebuilding it from scratch.
 *
 * Reuses the preview workflow: produces a NEW preview draft so the
 * user reviews the iteration before applying. Old preview is hard
 * deleted to avoid pile-up.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_iterate_page_design($input, $ctx) {
    $preview_id  = isset($input['from_preview_id']) ? (int) $input['from_preview_id'] : 0;
    $post_id     = isset($input['from_post_id'])    ? (int) $input['from_post_id']    : 0;
    $instruction = isset($input['instruction'])     ? trim((string) $input['instruction']) : '';

    // Fall back to ctx.post_id if the model omitted from_post_id but we
    // know which page the user is looking at. This is the most common
    // path after Apply — the chat has no fresh preview but the rail
    // knows the live post.
    if (!$preview_id && !$post_id && !empty($ctx['post_id'])) {
        $post_id = (int) $ctx['post_id'];
    }

    if (!$instruction) {
        return ['ok' => false, 'message' => 'Tell me what to change.'];
    }
    if (!$preview_id && !$post_id) {
        return ['ok' => false, 'message' => 'I need a preview or a page to iterate from.'];
    }

    $prior_html  = '';
    $original_id = 0;

    if ($preview_id) {
        $preview = get_post($preview_id);
        if (!$preview || $preview->post_type !== 'page' || !get_post_meta($preview_id, '_swcp_is_preview', true)) {
            // Preview gone — try post_id fallback if we have one.
            if ($post_id) {
                $preview_id = 0; // route via post_id branch below
            } else {
                return ['ok' => false, 'message' => 'The preview I would iterate from is not here anymore. Tell me to design a fresh one — or which page to work on.'];
            }
        } else {
            $original_id = (int) get_post_meta($preview_id, '_swcp_preview_of', true);
            if (!$original_id) {
                return ['ok' => false, 'message' => 'I lost the link between the preview and the original page.'];
            }
            $prior_html = (string) $preview->post_content;
        }
    }

    // post_id path — iterate directly on the live page content. v0.24.3.
    // v0.24.4 (Joost 2026-05-17): made resilient. If the post_id Claude
    // passed doesn't resolve, fall back to ctx.post_id (the rail knows
    // which page the user is on). Accept any post_status / post_type
    // that has content; the design lives in post_content regardless of
    // whether WordPress calls it 'page' or 'post'.
    if (!$preview_id && $post_id) {
        $live = get_post($post_id);
        if ((!$live || $live->post_status === 'trash') && !empty($ctx['post_id']) && (int) $ctx['post_id'] !== (int) $post_id) {
            $post_id = (int) $ctx['post_id'];
            $live = get_post($post_id);
        }
        if (!$live || $live->post_status === 'trash') {
            return ['ok' => false, 'message' => 'I cannot find that page. Open the page you want to extend and try again.'];
        }
        $original_id = (int) $live->ID;
        $prior_html  = (string) $live->post_content;
    }

    $original = get_post($original_id);

    // Strip wp:html markers so we send just the design HTML to the model.
    $prior_html = preg_replace('/<!--\s*\/?wp:html\s*-->/', '', $prior_html);
    $prior_html = trim($prior_html);
    if ($prior_html === '') {
        return ['ok' => false, 'message' => 'That page is empty — there is nothing to iterate on yet.'];
    }

    $url = SailWP_Copilot_Plugin::get_ai_proxy_url() . '/copilot/iterate-design';
    $body = wp_json_encode([
        'prior_html'    => $prior_html,
        'instruction'   => $instruction,
        'brand_profile' => class_exists('SailWP_Copilot_Brand_Profile')
            ? SailWP_Copilot_Brand_Profile::for_proxy()
            : null,
    ]);
    $response = wp_remote_post($url, [
        'timeout' => 60,
        'headers' => array_filter([
            'Content-Type'   => 'application/json',
            'X-License-Key'  => SailWP_Copilot_Plugin::get_license_key() ?: null,
            'X-Site-API-Key' => SailWP_Copilot_Plugin::get_site_api_key() ?: null,
        ]),
        'body' => $body,
    ]);
    if (is_wp_error($response)) {
        return ['ok' => false, 'message' => 'The iteration service did not respond. Try once more.'];
    }
    $code    = wp_remote_retrieve_response_code($response);
    $payload = json_decode(wp_remote_retrieve_body($response), true);
    if ($code === 402 && is_array($payload) && !empty($payload['limit_reached'])) {
        $upgrade = !empty($payload['upgrade_url']) ? $payload['upgrade_url'] : $payload['pricing_url'];
        return [
            'ok'              => false,
            'limit_reached'   => true,
            'message'         => $payload['message'],
            'upgrade_url'     => $upgrade,
            'pricing_url'     => $payload['pricing_url'],
            'plan'            => $payload['plan'] ?? 'free',
            'inline_upgrade'  => $payload['inline_upgrade'] ?? null,
        ];
    }
    if ($code >= 400 || empty($payload['ok']) || empty($payload['html'])) {
        $msg = is_array($payload) && !empty($payload['message']) ? $payload['message'] : 'Could not iterate the design.';
        return ['ok' => false, 'message' => $msg];
    }
    $design_html = (string) $payload['html'];
    $new_content = "<!-- wp:html -->\n" . $design_html . "\n<!-- /wp:html -->";

    // Purge any other preview drafts for this original page before
    // creating a new one. Handles the post_id-branch where there is
    // no $preview_id to delete below, plus any stragglers from earlier
    // sessions. Defined in design-page-preview.php.
    if (function_exists('swcp_purge_existing_previews_for')) {
        swcp_purge_existing_previews_for($original_id);
    }

    // Create a NEW preview draft. We hard-delete the previous preview
    // (if there was one) below for backward-compat with $preview_id
    // path — the purge above already handled the post_id path.
    $new_preview_id = wp_insert_post([
        'post_type'    => 'page',
        'post_status'  => 'draft',
        'post_title'   => ($original ? get_the_title($original) : 'Page') . ' (preview)',
        'post_name'    => ($original ? $original->post_name : 'page') . '-preview-' . wp_generate_uuid4(),
        'post_content' => $new_content,
    ], true);
    if (is_wp_error($new_preview_id) || !$new_preview_id) {
        return ['ok' => false, 'message' => 'Iterated the design but could not save the new preview.'];
    }
    update_post_meta($new_preview_id, '_swcp_preview_of', $original_id);
    update_post_meta($new_preview_id, '_swcp_is_preview', 1);

    // Delete the old preview now that we have a fresh one.
    wp_delete_post($preview_id, true);

    $preview_url = add_query_arg('swcp_render_preview', $new_preview_id, home_url('/'));

    return [
        'ok'           => true,
        'message'      => 'Iterated the design with your tweak. The updated preview just slid in. Your live page is still untouched.',
        'preview_id'   => (int) $new_preview_id,
        'original_id'  => $original_id,
        'preview_url'  => $preview_url,
        'view_url'     => $preview_url,
    ];
}
