<?php
// components/Assistant/FlowUtils.php
namespace Components\Assistant;

class FlowUtils
{
    /**
     * Resolve the current flow identifier and YAML path based on request params.
     * Priority:
     *   1) explicit 'flow' param (string id)
     *   2) map known 'module' to a flow id
     *   3) default flow
     *
     * Returns array [flowId, yamlPath]
     */
    public static function resolveFlowAndYaml(): array
    {
        $flow = self::req('flow');
        $module = self::req('module');
        // Mock mapping: module -> flow id
        // You can extend this mapping in the future.
        $moduleToFlow = [
            // Use a blueprint example to demonstrate that non-assistant YAML can be converted
            'blueprint' => 'blueprint',
            // Example specific modules could map to custom flows
            'newsletter' => 'newsletter',
            'automation' => 'automation',
        ];

        if ($flow === '') {
            $flow = $moduleToFlow[$module] ?? 'default';
        }

        // Map flow id -> YAML path
        $root = defined('BEEZUI_ROOT') ? (string)constant('BEEZUI_ROOT') : dirname(__DIR__, 2);
        $flowsDir = $root . '/components/Assistant/views';
        $map = [
            'default' => $flowsDir . '/flow.yaml',
            'newsletter' => $flowsDir . '/flow.yaml', // for now reuse default
            'automation' => $flowsDir . '/flow.yaml', // for now reuse default
            'blueprint' => $root . '/blueprint.yaml',
        ];

        $yaml = $map[$flow] ?? $map['default'];
        return [$flow, $yaml];
    }

    /**
     * Compute a namespaced state key used to isolate session state per flow.
     */
    public static function stateKeyFor(string $flowId): string
    {
        $module = self::req('module');
        $parts = ['assistant', $flowId ?: 'default'];
        if ($module !== '') $parts[] = $module;
        return implode(':', $parts);
    }

    /**
     * Read request parameter from either GET or POST (POST takes precedence during submissions)
     */
    public static function req(string $name): string
    {
        // Prefer POST submissions over GET; sanitize as string
        $rawPost = \mh_post($name, null);
        if ($rawPost !== null) {
            return (string) \mh_post($name, '', 'string');
        }
        return (string) \mh_get($name, '', 'string');
    }
}
