<?php

namespace GriffinForms\Includes\Ai;

use GriffinForms\Includes\Ai\PromptRegistry\PromptRegistry;

class OperationPlanner
{
    protected PromptRegistry $registry;

    public function __construct(PromptRegistry $registry)
    {
        $this->registry = $registry;
    }

    public function plan(
        ClassificationResult $classification,
        int $form_id,
        string $prompt,
        array $selected_context,
        array $request_context,
        string $provider,
        array $route_config
    ): OperationPlan {
        $base_config = array_merge(
            $route_config,
            [
                'selected_context' => $selected_context,
                'request_context'  => $request_context,
            ]
        );

        if ($classification->type === 'batch') {
            $items = [];
            foreach ($classification->batch_items as $batch_item) {
                $handler_key = sanitize_key((string) ($batch_item['handler_key'] ?? ''));
                $item_label  = (string) ($batch_item['label'] ?? $handler_key);
                $item_config = array_merge($base_config, [
                    'apply_patch_plan' => true,
                    'item_type'        => (string) ($batch_item['type'] ?? ''),
                    'item_id'          => (int) ($batch_item['id'] ?? 0),
                ]);
                $items[] = new OperationItem($handler_key, $item_config, $item_label);
            }
            return new OperationPlan($items);
        }

        $handler_key = $classification->handler_key;
        $apply_patch = ($request_context['response_family'] ?? 'mutation') === 'mutation';

        $config = array_merge($base_config, ['apply_patch_plan' => $apply_patch]);

        // Suggestion short-circuits carry their own merged config from BuilderAssistRouter.
        // For all other types, assemble the standard config here.
        $label = $classification->item_type !== ''
            ? ucfirst($classification->item_type) . ($classification->item_id > 0 ? ' #' . $classification->item_id : '')
            : $handler_key;

        return new OperationPlan([new OperationItem($handler_key, $config, $label)]);
    }
}
