<?php

namespace App\Services;

use Carbon\Carbon;
use App\Services\AgentAIService;
use Carbon\CarbonInterface;

class AgentParserService
{
    public static function parse(string $input, array $model): array
    {
        $text = strtolower($input);

        // 🔥 1. IMMER zuerst AI
        $ai = AgentAIService::parse($input, $model);

        $aiData  = $ai['data'] ?? ['type' => 'unknown', 'data' => []];
        $aiUsage = $ai['usage'] ?? null;

        if (($ai['type'] ?? 'unknown') !== 'unknown') {
            return $ai;
        }

        // 🔥 2. FALLBACK → einfacher Parser
        if (self::isEvent($text)) {
            return self::parseEvent($text);
        }

        if (self::isNote($text)) {
            return self::parseNote($text);
        }

        // 🔥 3. GAR NICHTS ERKANNT
        return [
            'type' => 'unknown',
            'data' => [],
        ];
    }

    protected static function isEvent(string $text): bool
    {
        return str_contains($text, 'termin');
    }

    protected static function isNote(string $text): bool
    {
        return str_contains($text, 'notiz');
    }

    protected static function parseEvent(string $text): array
    {
        $datetime = self::extractDateTime($text);

        // 🔥 saubere Titel-Extraktion
        $title = preg_replace('/termin|morgen|heute|\d{1,2}:\d{2}|\d{1,2}\s*uhr/', '', $text);
        $title = ucfirst(trim($title));

        return [
            'type' => 'event',
            'data' => [
                'title' => $title,
                'datetime' => $datetime?->toDateTimeString(),
            ],
        ];
    }

    protected static function parseNote(string $text): array
    {
        $content = trim(str_replace('notiz', '', $text));

        return [
            'type' => 'note',
            'data' => [
                'content' => ucfirst($content),
            ],
        ];
    }

    protected static function extractDateTime(string $text): ?CarbonInterface
    {
        $date = now();

        // 🔥 NEU: "in X tagen"
        if (preg_match('/in\s+(\d+)\s+tagen/', $text, $matches)) {
            $date = now()->addDays((int)$matches[1]);
        }

        // 🔥 OPTIONAL
        if (str_contains($text, 'übermorgen')) {
            $date = now()->addDays(2);
        }

        if (str_contains($text, 'morgen')) {
            $date = now()->addDay();
        }

        if (str_contains($text, 'heute')) {
            $date = now();
        }

        // 🔥 15:00
        if (preg_match('/(\d{1,2}):(\d{2})/', $text, $matches)) {
            return $date->copy()->setTime($matches[1], $matches[2]);
        }

        // 🔥 15 uhr
        if (preg_match('/(\d{1,2})\s*uhr/', $text, $matches)) {
            return $date->copy()->setTime($matches[1], 0);
        }

        return null;
    }
}
