<?php

declare(strict_types=1);

final class Asm3IntakeRecovery
{
    private const CITIES = [
        'Betton' => ['betton', 'beton'],
        'Brignogan-Plages' => ['brignogan'],
        'Fougères' => ['fougère', 'fougeres'],
        'Gouesnou' => ['gouesnou'],
        'Goulven' => ['goulven'],
        'Guissény' => ['guissény', 'guisseny'],
        'Kernouës' => ['kernouës', 'kernoues'],
        'Kerlouan' => ['kerlouan'],
        'Landerneau' => ['landerneau'],
        'Lanhouarneau' => ['lanhouarneau'],
        'Landivisiau' => ['landivisiau'],
        'Le Drennec' => ['le drennec'],
        'Le Folgoët' => ['le folgoët', 'le folgoet', 'du folgoët', 'du folgoet'],
        'Lesneven' => ['lesneven', 'lesnevenet'],
        'Perros-Guirec' => ['perros guirec', 'perros guierrec'],
        'Ploudaniel' => ['ploudaniel'],
        'Plouescat' => ['plouescat'],
        'Plouguerneau' => ['plouguerneau'],
        'Plouider' => ['plouider'],
        'Plounéour-Brignogan-Plages' => [
            'plounéour trez',
            'plouneour trez',
            'plounéour brignogan plage',
            'plouneour brignogan plage',
        ],
        'Plounévez-Lochrist' => ['plounevez lochrist', 'plounévez lochrist'],
        'Plouzané' => ['plouzané', 'plouzane'],
        'Saint-Frégant' => ['saint frégant', 'saint fregant'],
        'Saint-Méen' => ['saint méen', 'saint meen'],
        'Saint-Pol-de-Léon' => ['saint pol de leon', 'saint-pol-de-léon'],
    ];

    public static function reason(array $row): string
    {
        return trim((string) ($row['REASONFORENTRY'] ?? ''));
    }

    public static function municipality(string $reason): ?string
    {
        $text = self::plain($reason);
        if ($text === '') {
            return null;
        }
        $found = [];
        foreach (self::CITIES as $city => $aliases) {
            foreach ($aliases as $alias) {
                if (str_contains($text, self::plain($alias))) {
                    $found[$city] = true;
                    break;
                }
            }
        }
        if (count($found) !== 1) {
            return null;
        }
        $city = (string) array_key_first($found);
        $words =
            'trouv|errant|recueill|recup|ramass|vient|arriv|fourriere|mairie|police municipale|jardin|terrain|ferme|hangar|grange|ne dans|abandonn|signal';
        if (preg_match('/^\s*' . self::cityPattern($city) . '\b/u', $text)) {
            return $city;
        }
        if (preg_match('/(?:' . $words . ').{0,100}' . self::cityPattern($city) . '/u', $text)) {
            return $city;
        }
        if (preg_match('/' . self::cityPattern($city) . '.{0,55}(?:' . $words . ')/u', $text)) {
            return $city;
        }
        return null;
    }

    private static function cityPattern(string $city): string
    {
        $parts = [];
        foreach (self::CITIES[$city] as $alias) {
            $parts[] = preg_quote(self::plain($alias), '/');
        }
        return '(?:' . implode('|', $parts) . ')';
    }
    private static function plain(string $value): string
    {
        $value = mb_strtolower(trim($value));
        $v = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
        return preg_replace('/\s+/u', ' ', is_string($v) ? $v : $value) ?? $value;
    }
}
