<?php
/**
 * سودانا — BehaviorEngine v1
 * Separates ASSISTANT (user-facing) from AGENT (backend execution)
 *
 * ASSISTANT: user sees → friendly, guides, explains
 * AGENT:     backend   → executes tools, writes DB, processes events
 *
 * This engine controls:
 * 1. Tone mapping per service
 * 2. Conversion scoring
 * 3. CTA injection
 * 4. Response shaping
 */
class BehaviorEngine {

    // ── TONE MAP — per service ─────────────────────────────────
    private static array $toneMap = [
        'medical'   => ['mood'=>'calm',     'label'=>'هادئ وداعم',     'emoji'=>'⚕️'],
        'family'    => ['mood'=>'warm',     'label'=>'دافئ ومهتم',     'emoji'=>'👨‍👩‍👧'],
        'legal'     => ['mood'=>'precise',  'label'=>'دقيق ومحترم',    'emoji'=>'⚖️'],
        'business'  => ['mood'=>'push',     'label'=>'إيجابي وعملي',   'emoji'=>'💼'],
        'academy'   => ['mood'=>'guide',    'label'=>'مُشجع وتعليمي',  'emoji'=>'🎓'],
        'market'    => ['mood'=>'active',   'label'=>'نشيط وتجاري',    'emoji'=>'🛒'],
        'community' => ['mood'=>'friendly', 'label'=>'ودود ومجتمعي',   'emoji'=>'🏘️'],
        'pharmacy'  => ['mood'=>'helpful',  'label'=>'مفيد وسريع',     'emoji'=>'💊'],
        'developer' => ['mood'=>'technical','label'=>'تقني ومختصر',    'emoji'=>'⚡'],
        'platform'  => ['mood'=>'sales',    'label'=>'مقنع ومبيعاتي',  'emoji'=>'🇸🇩'],
        'pay'       => ['mood'=>'secure',   'label'=>'موثوق وواضح',    'emoji'=>'💳'],
        'vision'    => ['mood'=>'helpful',  'label'=>'مفيد وتحليلي',   'emoji'=>'🔍'],
        'general'   => ['mood'=>'friendly', 'label'=>'ودود وواضح',     'emoji'=>'✨'],
    ];

    // ── CTA MAP — per service ─────────────────────────────────
    private static array $ctaMap = [
        'medical'   => ['label'=>'احجز مع طبيب الآن',    'url'=>'/'],
        'legal'     => ['label'=>'احجز استشارة قانونية', 'url'=>'/'],
        'business'  => ['label'=>'ابدأ مشروعك الآن',     'url'=>'/'],
        'platform'  => ['label'=>'انضم مجاناً',           'url'=>'/'],
        'general'   => ['label'=>'اكتشف سودانا',         'url'=>'/'],
        'developer' => ['label'=>'احصل على API Key',     'url'=>'/dashboard/'],
        'pay'       => ['label'=>'شحن محفظتك الآن',       'url'=>'/'],
        'vision'    => ['label'=>'ارفع صورة للتحليل',     'url'=>'/'],
        'academy'   => ['label'=>'ابدأ التعلم',          'url'=>'/'],
        'market'    => ['label'=>'انشر إعلانك',          'url'=>'/'],
        'pharmacy'  => ['label'=>'اطلب وصفتك',           'url'=>'/'],
    ];

    /**
     * compose() — called by Gateway before returning response
     * Returns behavior metadata to enrich the response
     */
    public static function compose(array $ctx): array {
        $service = $ctx['service'] ?? 'general';
        $source  = $ctx['source']  ?? 'ie';
        $score   = self::conversionScore($ctx);

        $tone = self::$toneMap[$service] ?? self::$toneMap['general'];
        $cta  = self::$ctaMap[$service]  ?? self::$ctaMap['general'];

        return [
            'tone'             => $tone['mood'],
            'tone_label'       => $tone['label'],
            'emoji'            => $tone['emoji'],
            'conversion_score' => $score,
            'cta'              => $score >= 5 ? $cta : null,
            'separator'        => self::separator($score),
        ];
    }

    /**
     * conversionScore() — how ready is the user to convert?
     * 0-2: casual | 3-4: interested | 5-6: engaged | 7+: ready
     */
    public static function conversionScore(array $ctx): int {
        $score = 0;
        if (!empty($ctx['flow_active']))    $score += 3; // in a flow = high intent
        if (!empty($ctx['step_completed'])) $score += 2; // completed step = very engaged
        if (!empty($ctx['ie_hit']))         $score += 1; // IE answered = knows the platform
        if (!empty($ctx['user_id']))        $score += 1; // logged in = committed
        if ($ctx['source'] === 'flow')      $score += 2; // flow response = action taken
        if (($ctx['service'] ?? '') === 'platform') $score += 1; // exploring platform
        return min($score, 10);
    }

    /**
     * separator() — what separator to show before CTA
     */
    private static function separator(int $score): string {
        if ($score >= 7) return 'strong';
        if ($score >= 5) return 'medium';
        if ($score >= 3) return 'soft';
        return 'none';
    }

    /**
     * formatAnswer() — wraps the answer with behavior tone
     * Called by OutputBuilder to shape the final response
     */
    public static function formatAnswer(string $answer, string $service): string {
        // Add service-appropriate closing if not already present
        $tone = self::$toneMap[$service] ?? self::$toneMap['general'];
        if ($service === 'medical' && !str_contains($answer, '⚕️')) {
            $answer .= "\n\n⚕️ استشر طبيبك للتشخيص الدقيق.";
        }
        if ($service === 'legal' && !str_contains($answer, 'محامٍ') && !str_contains($answer, 'محامي')) {
            $answer .= "\n\n⚖️ راجع محامياً لاستشارة قانونية ملزِمة.";
        }
        return $answer;
    }
}
