<?php

namespace GriffinForms\Includes\Ai;

class AssistFailureFramework
{
    public function build(string $status, int $code, array $context = [], ?string $message_override = null): array
    {
        $status = sanitize_key($status);
        $family = $this->familyForStatus($status);
        $message = $message_override !== null && trim($message_override) !== ''
            ? $message_override
            : $this->messageFor($status, $context);

        return [
            'success' => false,
            'status' => $status,
            'family' => $family,
            'message' => $message,
            'code' => $code,
            'mutated_ids' => [],
            'suggestions' => $this->suggestionsFor($status, $context),
        ];
    }

    protected function familyForStatus(string $status): string
    {
        return match ($status) {
            'clarification_required', 'selection_required', 'empty_prompt' => 'clarification',
            'unsupported_surface', 'unsupported_origin', 'unsupported_response_mode', 'unsupported_prompt_key', 'missing_handler', 'route_mismatch' => 'unsupported',
            'provider_unavailable', 'provider_error', 'timeout' => 'provider',
            'destructive_additive_blocked', 'ambiguous_reorder_intent', 'selected_edit_apply_failed', 'patch_apply_failed', 'bulk_text_apply_failed' => 'unsafe_mutation_blocked',
            'validation_failed', 'patch_plan_validation_failed', 'bulk_text_validation_failed', 'advisory_validation_failed' => 'validation_failed',
            'consent_required' => 'consent_required',
            default => 'failure',
        };
    }

    protected function messageFor(string $status, array $context): string
    {
        $chat_mode = !empty($context['chat_mode']);

        return match ($status) {
            'invalid_form' => __('Griffin Assist could not find the draft you were working on. Refresh the page and try again.', 'griffinforms-form-builder'),
            'empty_prompt' => $chat_mode
                ? __('Ask Griffin Assist a question or describe the idea you want help with.', 'griffinforms-form-builder')
                : __('Describe the change you want Griffin Assist to make.', 'griffinforms-form-builder'),
            'clarification_required' => __('I need a clearer instruction before I can continue safely. Try naming the exact element or the exact change you want.', 'griffinforms-form-builder'),
            'selection_required' => __('Select the page, row, column, or field you want to change so Griffin Assist can stay scoped correctly.', 'griffinforms-form-builder'),
            'unsupported_surface' => __('Griffin Assist is not available on this admin screen yet.', 'griffinforms-form-builder'),
            'unsupported_origin' => __('That Griffin Assist action path is not supported yet.', 'griffinforms-form-builder'),
            'unsupported_response_mode' => __('This Griffin Assist mode is not available yet for the current request.', 'griffinforms-form-builder'),
            'unsupported_prompt_key' => __('I understand the request, but that workflow is not supported here yet.', 'griffinforms-form-builder'),
            'missing_handler' => __('The requested Griffin Assist workflow is not ready right now.', 'griffinforms-form-builder'),
            'provider_unavailable' => __('AI is not configured yet. Set up a provider in Settings → AI and try again.', 'griffinforms-form-builder'),
            'provider_error' => __('The AI provider could not complete that request. Check the AI settings and try again.', 'griffinforms-form-builder'),
            'timeout' => __('Griffin Assist took too long to respond, so nothing was changed. Try a shorter or more specific request.', 'griffinforms-form-builder'),
            'destructive_additive_blocked' => __('I stopped that change because it looked like it would overwrite existing form content instead of preserving it.', 'griffinforms-form-builder'),
            'ambiguous_reorder_intent' => __('I need a clearer ordering instruction before I can rearrange items safely.', 'griffinforms-form-builder'),
            'selected_edit_apply_failed' => __('I could not apply that change to the selected element without risking the rest of the draft.', 'griffinforms-form-builder'),
            'patch_apply_failed' => __('I could build the patch plan, but I could not apply it safely to the draft.', 'griffinforms-form-builder'),
            'bulk_text_apply_failed' => __('I could prepare the bulk text changes, but I could not apply them safely.', 'griffinforms-form-builder'),
            'validation_failed' => __('I could not turn that into a safe Griffin Assist response yet. Try naming the exact element and exact change.', 'griffinforms-form-builder'),
            'patch_plan_validation_failed' => __('I could not turn that into a safe patch plan yet. Try naming the exact target and the exact change you want.', 'griffinforms-form-builder'),
            'bulk_text_validation_failed' => __('I could not turn that into safe bulk text changes yet. Try naming the exact text family you want to update.', 'griffinforms-form-builder'),
            'advisory_validation_failed' => __('I could not shape that into a guided reply yet. Try asking for one specific target or one exact change.', 'griffinforms-form-builder'),
            'pipeline_error' => __('Griffin Assist hit an unexpected problem before any changes were applied. Please try again.', 'griffinforms-form-builder'),
            'consent_required' => __('Before using AI here, review and accept the data-sharing acknowledgement in Settings → AI.', 'griffinforms-form-builder'),
            default => __('Griffin Assist could not complete that request safely.', 'griffinforms-form-builder'),
        };
    }

    protected function suggestionsFor(string $status, array $context): array
    {
        $surface = sanitize_key((string) ($context['surface'] ?? 'form_builder'));

        return match ($status) {
            'clarification_required' => [
                __('Name the exact element you want to change.', 'griffinforms-form-builder'),
                __('Describe the exact text or structure change you want.', 'griffinforms-form-builder'),
            ],
            'selection_required' => [
                __('Select an element in the builder first.', 'griffinforms-form-builder'),
                __('Then retry the request with the element still selected.', 'griffinforms-form-builder'),
            ],
            'provider_unavailable', 'provider_error' => [
                __('Open Settings → AI and verify the configured provider.', 'griffinforms-form-builder'),
                __('Then retry the request.', 'griffinforms-form-builder'),
            ],
            'consent_required' => [
                __('Open Settings → AI and acknowledge external AI data sharing.', 'griffinforms-form-builder'),
                __('Then retry the request from the same screen.', 'griffinforms-form-builder'),
            ],
            'destructive_additive_blocked' => [
                __('Ask Griffin Assist to preserve the current form and append only the new content.', 'griffinforms-form-builder'),
            ],
            'ambiguous_reorder_intent' => [
                __('Try “move Email after Name” or “put Message last”.', 'griffinforms-form-builder'),
            ],
            'bulk_text_validation_failed' => [
                __('Try naming the exact text family you want to update.', 'griffinforms-form-builder'),
                __('Then say the exact change you want made.', 'griffinforms-form-builder'),
            ],
            'unsupported_surface' => $surface === 'form_builder'
                ? []
                : [__('Use Griffin Assist from a supported admin surface.', 'griffinforms-form-builder')],
            default => [],
        };
    }
}
