<?php

namespace App\Support;

/**
 * Mirrors inferGoalInput from bugets-smart-money/src/lib/smart-form.ts (goalRulebook + monthly suggestion).
 */
final class GoalInference
{
    /** @var list<array{match: list<string>, icon: string, priority: string}> */
    private const GOAL_RULEBOOK = [
        ['match' => ['emergency', 'safety', 'rainy day'], 'icon' => '🛡️', 'priority' => 'high'],
        ['match' => ['vacation', 'trip', 'travel', 'holiday'], 'icon' => '✈️', 'priority' => 'medium'],
        ['match' => ['laptop', 'computer', 'macbook', 'iphone', 'phone', 'tablet'], 'icon' => '💻', 'priority' => 'high'],
        ['match' => ['house', 'home', 'mortgage', 'rent', 'down payment', 'hipoteca', 'aluguel'], 'icon' => '🏠', 'priority' => 'high'],
        ['match' => ['pet', 'pets', 'dog', 'cat', 'veterinary'], 'icon' => '🐾', 'priority' => 'medium'],
        ['match' => ['car', 'auto', 'vehicle', 'motorcycle', 'bike'], 'icon' => '🚗', 'priority' => 'medium'],
        ['match' => ['wedding', 'marriage'], 'icon' => '💍', 'priority' => 'medium'],
        ['match' => ['baby', 'nursery', 'childcare'], 'icon' => '👶', 'priority' => 'high'],
        ['match' => ['investment', 'retirement', 'pension', 'etf', 'stocks'], 'icon' => '📈', 'priority' => 'low'],
    ];

    /**
     * @return array{
     *     icon?: string,
     *     priority?: string,
     *     monthlyContribution?: int,
     *     suggestions: list<array{id: string, label: string, detail?: string, tone?: string}>
     * }
     */
    public static function infer(string $name, string $target, string $deadline, string $saved, array $history = []): array
    {
        $input = mb_strtolower(trim($name));
        $suggestions = [];
        $result = ['suggestions' => $suggestions];

        foreach (self::GOAL_RULEBOOK as $rule) {
            if (! FinancialKeywordMatch::containsAny($name, $rule['match'])) {
                continue;
            }
            $result['icon'] = $rule['icon'];
            $result['priority'] = $rule['priority'];
            $tone = $rule['priority'] === 'high' ? 'warning' : 'positive';
            $suggestions[] = [
                'id' => 'goal-'.$rule['icon'],
                'label' => 'Set '.$rule['priority'].' priority',
                'tone' => $tone,
            ];
            $result['suggestions'] = $suggestions;
            break;
        }

        $targetNum = (float) ($target !== '' ? $target : 0);
        $savedNum = (float) ($saved !== '' ? $saved : 0);
        if ($deadline !== '' && $targetNum > $savedNum) {
            $deadlineTs = strtotime($deadline.' 12:00:00 UTC');
            $nowTs = time();
            if ($deadlineTs !== false && $deadlineTs > $nowTs) {
                $msDiff = ($deadlineTs - $nowTs) * 1000;
                $monthsLeft = max(1, (int) ceil($msDiff / (1000 * 60 * 60 * 24 * 30)));
                $monthly = (int) ceil(($targetNum - $savedNum) / $monthsLeft);
                $result['monthlyContribution'] = $monthly;
                $suggestions[] = [
                    'id' => 'monthly',
                    'label' => 'Suggested monthly contribution €'.$monthly,
                    'detail' => 'To reach the target in about '.$monthsLeft.' months',
                    'tone' => 'positive',
                ];
                $result['suggestions'] = $suggestions;
            }
        }

        // Learn from similar goals and existing monthly behavior.
        $nameTokens = array_values(array_filter(preg_split('/[^a-z0-9]+/i', $input ?: '')));
        $bestScore = 0;
        $bestRow = null;
        foreach ($history as $row) {
            if (! is_array($row)) {
                continue;
            }
            $rowName = mb_strtolower((string) ($row['name'] ?? ''));
            if ($rowName === '') {
                continue;
            }
            $score = 0;
            foreach ($nameTokens as $token) {
                if (mb_strlen($token) < 3) {
                    continue;
                }
                if (str_contains($rowName, $token)) {
                    $score++;
                }
            }
            if ($score > $bestScore) {
                $bestScore = $score;
                $bestRow = $row;
            }
        }
        if ($bestRow !== null && $bestScore > 0) {
            if (empty($result['icon']) && ! empty($bestRow['icon'])) {
                $result['icon'] = (string) $bestRow['icon'];
            }
            if (empty($result['priority']) && ! empty($bestRow['priority'])) {
                $result['priority'] = (string) $bestRow['priority'];
            }
            if (! isset($result['monthlyContribution']) && isset($bestRow['monthlyContribution']) && is_numeric($bestRow['monthlyContribution'])) {
                $result['monthlyContribution'] = (int) round((float) $bestRow['monthlyContribution']);
                $suggestions[] = [
                    'id' => 'history-monthly',
                    'label' => 'Predicted contribution from similar goal',
                    'detail' => 'Auto-suggested €'.number_format((float) $bestRow['monthlyContribution'], 0, ',', '.').' / month',
                    'tone' => 'positive',
                ];
            }
        }

        return $result;
    }
}
