File size: 48,221 Bytes
0dd5490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
"""Text normalisation for the AMLC 2026 business entity resolution pipeline.

Pure standard library (``re`` + ``unicodedata``). Public API:

    fix_encoding(s)                         -> str        repair mojibake / C1 controls / zero-width chars
    clean_text(s, strip_prefixes=True)      -> str        generic cleaner (accents, junk, punctuation)
    normalize_name(s, country='')           -> NameNorm
    normalize_address(s, country)           -> AddrNorm
    normalize_record(name, address, country)-> dict       flat dict of both + blocking keys
    blocking_keys(name_norm, addr_norm, country, token_df=None) -> list[str]
    transliterate_indic(s)                  -> None       stub, filled by a later module
    blocking_normalizer(df)                 -> polars DataFrame adapter for src.blocking --normalizer

Design notes
------------
* ``country`` is an open string set. Every country-specific behaviour is a dict lookup
  (``_COUNTRY_CFG.get(key, default)``); an unseen country falls back to generic rules, never errors.
* Accent folding strips only *Latin* combining marks (U+0300-036F etc.), so Indic vowel signs and
  viramas survive and Indic words are not broken.
* Names: legal forms are removed from ``core`` wherever they sit (start, end, middle, bracketed,
  reordered, doubled); generic words (services, center, group ...) stay in ``core``.
  Alias forms "X f/k/a Y", "X dba Y", "X formerly: Y" ... -> ``alt_names=[X, Y]`` and ``core=Y``
  (in this data Y is the real / S1 name and X a generated brand).
* Addresses: parts are classified (street / unit / other / district / state / numeric / null) and
  put in canonical order street, unit, other, district, state. ``city`` is the last "other" part
  (= the middle part of a 3-part address). French région names and département names are
  *recognised* (région -> ``state``, département -> ``district``) but never mapped to each other.
"""
from __future__ import annotations

import re
import unicodedata
from collections import Counter
from dataclasses import dataclass, field
from functools import lru_cache

__all__ = [
    "NameNorm", "AddrNorm", "fix_encoding", "fold_accents", "clean_text", "normalize_name",
    "normalize_address", "normalize_record", "blocking_keys", "transliterate_indic",
    "country_key", "blocking_normalizer",
]

# ----------------------------------------------------------------------------------------------
# 1. Encoding repair
# ----------------------------------------------------------------------------------------------
# 'Â\x80\x93' / 'â\x80\x99': UTF-8 bytes of U+2013 / U+2019 decoded as latin-1 (first byte mangled).
_MOJIBAKE_RE = re.compile("[\u00c2\u00e2]\u0080([\u0080-\u00bf])")
_MOJIBAKE_THIRD = {
    0x90: "-", 0x91: "-", 0x92: "-", 0x93: "-", 0x94: "-", 0x95: "-",
    0x98: "'", 0x99: "'", 0x9a: "'", 0x9b: "'",
    0x9c: '"', 0x9d: '"', 0x9e: '"',
}
# Same thing decoded as cp1252 instead of latin-1 ('’'): cheap to cover as well.
_CP1252_MOJIBAKE = {"\u00e2\u20ac\u2122": "'", "\u00e2\u20ac\u02dc": "'", "\u00e2\u20ac\u201c": "-",
                    "\u00e2\u20ac\u201d": "-", "\u00e2\u20ac\u0153": '"'}

_CHAR_FIX = {
    # C1 controls read as cp1252 punctuation; everything else in U+0080-009F is dropped
    **{cp: None for cp in range(0x80, 0xA0)},
    0x80: " ", 0x82: ",", 0x84: '"', 0x85: " ", 0x8B: " ", 0x91: "'", 0x92: "'", 0x93: '"',
    0x94: '"', 0x95: " ", 0x96: "-", 0x97: "-", 0x9B: " ",
    # zero-width / invisible
    0x200B: None, 0x200C: None, 0x200D: None, 0x2060: None, 0xFEFF: None, 0x00AD: None,
    # spaces, quotes, dashes, slashes
    0x00A0: " ", 0x2007: " ", 0x202F: " ", 0x3000: " ",
    0x2018: "'", 0x2019: "'", 0x201A: "'", 0x201B: "'", 0x2032: "'", 0x00B4: "'", 0x0060: "'",
    0x201C: '"', 0x201D: '"', 0x201E: '"', 0x00AB: '"', 0x00BB: '"',
    0x2010: "-", 0x2011: "-", 0x2012: "-", 0x2013: "-", 0x2014: "-", 0x2015: "-", 0x2212: "-",
    0x2044: "/", 0x2215: "/",
    0x00B0: "o",  # 'N°' -> 'No'  ('Nº' already becomes 'No' under NFKD)
}


def fix_encoding(s: str) -> str:
    """Repair double-encoded punctuation, C1 control characters and zero-width characters."""
    if not s:
        return ""
    if s.isascii():
        return s
    if "\u0080" in s:
        s = _MOJIBAKE_RE.sub(lambda m: _MOJIBAKE_THIRD.get(ord(m.group(1)), " "), s)
    if "\u20ac" in s:
        for bad, good in _CP1252_MOJIBAKE.items():
            s = s.replace(bad, good)
    return s.translate(_CHAR_FIX)


# ----------------------------------------------------------------------------------------------
# 2. Accent folding (Latin only)
# ----------------------------------------------------------------------------------------------
_LATIN_COMBINING_RE = re.compile("[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]")
_SPECIAL_LETTERS = str.maketrans({"ß": "ss", "æ": "ae", "œ": "oe", "ø": "o", "đ": "d", "ł": "l",
                                  "ı": "i", "þ": "th", "ð": "d", "ŀ": "l"})
_INDIC_RE = re.compile("[\u0900-\u0dff]")


def fold_accents(s: str) -> str:
    """NFKD + strip Latin combining marks. 'Résorts' -> 'Resorts', 'Fïls' -> 'Fils'. Indic untouched."""
    if s.isascii():
        return s
    s = unicodedata.normalize("NFKD", s)
    s = _LATIN_COMBINING_RE.sub("", s)
    return s.translate(_SPECIAL_LETTERS).translate(_CHAR_FIX)  # NFKD can emit U+2044 etc.


def _prep(s: str) -> str:
    """fix_encoding + lowercase + accent fold."""
    return fold_accents(fix_encoding(s).lower())


# ----------------------------------------------------------------------------------------------
# 3. Punctuation / token helpers shared by names and addresses
# ----------------------------------------------------------------------------------------------
def _build_punct_table() -> dict:
    table = {}
    for cp in range(0, 0x10000):
        if 0xD800 <= cp <= 0xDFFF:
            continue
        ch = chr(cp)
        if ch in "/-":
            continue
        cat = unicodedata.category(ch)
        if cat[0] in "PS" or cat == "Cc":
            table[cp] = " "
    return table


_PUNCT_TABLE = _build_punct_table()
_ACRONYM_RE = re.compile(r"(?<![a-z0-9])((?:[a-z]\.){1,}[a-z])\.?(?![a-z0-9])")  # s.a.r.l. -> sarl
_APOS_RE = re.compile(r"['\"]")
_ELISION_SPACE_RE = re.compile(r"(?<![a-z])([cdjlmnst]|qu)'\s+(?=[a-z])")  # "l' egalite" -> "l'egalite"
_WWW_RE = re.compile(r"\b(?:https?://)?www\.")
_DOMAIN_SUFFIX_RE = re.compile(r"(?<=[a-z0-9])\.(?:c[o0]m|co\.in|in|fr|net|org)\b")
_NULL_TOKEN_RE = re.compile(r"<\s*null\s*>|\bnull\b")
_HAS_DIGIT_RE = re.compile(r"\d")
_DIGITS_RE = re.compile(r"\d+")
_SEP_RUN_RE = re.compile(r"([-/])[-/]+")
_SEP_WORD_DIGIT_RE = re.compile(r"(?<=[a-z]{3})[-/](?=\d)|(?<=\d)[-/](?=[a-z]{3})|(?<=[a-z])[-/](?=[a-z])")
_SEP_ANY_RE = re.compile(r"[-/]+")


def _split_separators(text: str) -> list:
    """Whitespace-split; '-' and '/' become spaces unless inside a token that carries a digit
    ('C-6/24/1', '20/20' kept). Inside digit tokens, a >=3-letter word is split off
    ('sector-19' -> 'sector 19') while short prefixes stay ('dl-126')."""
    out = []
    for tok in text.split():
        if "-" not in tok and "/" not in tok:
            out.append(tok)
            continue
        tok = tok.strip("-/")
        if not tok:
            continue
        if not _HAS_DIGIT_RE.search(tok):
            out.extend(p for p in _SEP_ANY_RE.split(tok) if p)
            continue
        tok = _SEP_RUN_RE.sub(r"\1", tok)
        out.extend(p.strip("-/") for p in _SEP_WORD_DIGIT_RE.sub(" ", tok).split() if p.strip("-/"))
    return out


def _dedupe_adjacent(toks: list) -> list:
    """Drop immediately repeated alphabetic tokens ('Family Family Health', 'Unit UNIT 4')."""
    out = []
    for t in toks:
        if out and t == out[-1] and not t[:1].isdigit():
            continue
        out.append(t)
    return out


def _to_tokens(s: str) -> list:
    """Shared punctuation pipeline on an already lower-cased / folded string."""
    s = _ACRONYM_RE.sub(lambda m: m.group(1).replace(".", ""), s)
    if "'" in s:
        s = _ELISION_SPACE_RE.sub(r"\1'", s)
    s = _APOS_RE.sub("", s)
    s = s.translate(_PUNCT_TABLE)
    return _split_separators(s)


# ----------------------------------------------------------------------------------------------
# 4. clean_text (generic)
# ----------------------------------------------------------------------------------------------
_JUNK_EDGE_RE = re.compile(r"^(?:\s|--+|<<+|>>+|\|+|#+|\*+|!+)+|(?:\s|--+|<<+|>>+|\|+|#+|\*+|!+)+$")
_PREFIX_RE = re.compile(r"^(?:m\s*/\s*s\b\.?|messrs\b\.?|dr\b\.?)\s*")
_ID_RE = re.compile(r"\(\s*id\s*:?\s*\d+\s*\)|(?:(?<=\s)|^)#\d{3,}(?=\s|$)")
_PIPE_DOMAIN_TAIL_RE = re.compile(r"\s*\|\s*(?:https?://)?(?:www\.)?[a-z0-9.\-]+\.(?:c[o0]m|co\.in|in|fr|net|org)\s*$")


def clean_text(s: str, strip_prefixes: bool = True) -> str:
    """Generic cleaner: encoding repair, NFKD + strip accents, lowercase, '&' -> 'and', junk
    markers ('--', '<<', '>>', '|', '#', '##', '***') removed, brackets -> inner text, 'www.' and
    trailing '.com/.in/.fr/.c0m' stripped, 'null' dropped, leading 'm/s' / 'dr' dropped
    (strip_prefixes), punctuation -> spaces except '-' and '/' inside digit-bearing tokens."""
    if not s:
        return ""
    s = _prep(s)
    s = _ID_RE.sub(" ", s)
    s = _PIPE_DOMAIN_TAIL_RE.sub("", s)
    s = _JUNK_EDGE_RE.sub("", s)
    if strip_prefixes:
        s = _PREFIX_RE.sub("", s)
    s = _WWW_RE.sub("", s)
    s = _DOMAIN_SUFFIX_RE.sub("", s)
    s = _NULL_TOKEN_RE.sub(" ", s)
    s = s.replace("&", " and ").replace("#", " ")
    return " ".join(_to_tokens(s))


# ----------------------------------------------------------------------------------------------
# 5. Country handling (open set)
# ----------------------------------------------------------------------------------------------
_COUNTRY_ALIASES = {
    "us": "us", "usa": "us", "u s": "us", "u s a": "us", "united states": "us",
    "united states of america": "us", "america": "us",
    "india": "india", "in": "india", "ind": "india", "bharat": "india",
    "france": "france", "fr": "france", "fra": "france", "republique francaise": "france",
}


@lru_cache(maxsize=1024)
def country_key(country) -> str:
    """Canonical lowercase key. Known aliases collapse ('USA' -> 'us'); anything else is kept
    as its own folded lowercase string, so new countries flow through generic rules."""
    if not country:
        return ""
    k = " ".join(_prep(str(country)).replace(".", " ").split())
    return _COUNTRY_ALIASES.get(k, k)


# ----------------------------------------------------------------------------------------------
# 6. Names
# ----------------------------------------------------------------------------------------------
STRONG, EDGE, SUFFIX, PAIR = "strong", "edge", "suffix", "pair"
# token -> (canonical, kind). STRONG: removed anywhere. EDGE: removed at either edge / next to a
# legal token / right before a trailing generic word. SUFFIX ('private', 'public'): right edge,
# next to a legal token, or anywhere once ltd/limited is present. PAIR: only before ltd/limited.
_LEGAL_COMMON = {
    "inc": ("inc", STRONG), "incorporated": ("inc", STRONG), "corp": ("corp", STRONG),
    "corporation": ("corp", STRONG), "co": ("co", EDGE), "company": ("co", EDGE),
    "llc": ("llc", STRONG), "ltd": ("ltd", STRONG), "limited": ("ltd", STRONG),
    "llp": ("llp", STRONG), "pllc": ("pllc", STRONG), "pc": ("pc", STRONG), "plc": ("plc", STRONG),
    "lp": ("lp", STRONG),
    "pvt": ("pvt", STRONG), "private": ("pvt", SUFFIX), "opc": ("opc", EDGE), "public": ("public", SUFFIX),
}
_LEGAL_FRANCE = {
    "sarl": ("sarl", STRONG), "sas": ("sas", STRONG), "sasu": ("sasu", STRONG), "eurl": ("eurl", STRONG),
    "sa": ("sa", EDGE), "sci": ("sci", EDGE), "snc": ("snc", EDGE), "scp": ("scp", EDGE),
    "ei": ("ei", EDGE), "scop": ("scop", EDGE), "gie": ("gie", EDGE),
    "ets": ("ets", EDGE), "etablissements": ("ets", EDGE), "etablissement": ("ets", EDGE),
}
# Indic-script spellings seen in S2/S3 India names (limited / private / pra. / li. / LLP).
_LEGAL_INDIC_RAW = {
    "ltd": ["लिमिटेड", "लि", "లిమిటెడ్", "ಲಿಮಿಟೆಡ್", "லிமிடெட்", "লিমিটেড", "લિમિટેડ", "લિ",
            "ലിമിറ്റഡ്", "ଲିମିଟେଡ୍", "ਲਿਮਟਿਡ", "ਲਿਮਿਟੇਡ", "ਲਿ"],
    "pvt": ["प्राइवेट", "प्रा", "ప్రైవేట్", "ಪ್ರೈವೇಟ್", "பிரைவேட்", "প্রাইভেট", "પ્રાઇવેટ", "પ્રા",
            "പ്രൈവറ്റ്", "ପ୍ରାଇଭେଟ୍", "ਪ੍ਰਾਈਵੇਟ", "ਪ੍ਰਾ"],
    "llp": ["एलएलपी", "ఎల్ఎల్పీ", "ಎಲ್ಎಲ್ಪಿ", "எல்எல்பி", "એલએલપી", "এলএলপি", "എൽഎൽപി", "ଏଲ୍ଏଲ୍ପି"],
}
_LEGAL_INDIC = {}
for _canon, _words in _LEGAL_INDIC_RAW.items():
    for _w in _words:
        _kind = SUFFIX if _canon == "pvt" else STRONG
        _LEGAL_INDIC[_prep(_w)] = (_canon, _kind)

_LEGAL_BY_COUNTRY = {
    "us": {**_LEGAL_COMMON, **_LEGAL_INDIC},
    "india": {**_LEGAL_COMMON, **_LEGAL_INDIC},
    "france": {**_LEGAL_COMMON, **_LEGAL_FRANCE, **_LEGAL_INDIC},
}
_LEGAL_DEFAULT = {**_LEGAL_COMMON, **_LEGAL_FRANCE, **_LEGAL_INDIC}
_LEGAL_ORDER = ["public", "pvt", "opc", "ltd", "llp", "llc", "pllc", "inc", "corp", "co", "pc", "plc",
                "lp", "sarl", "sasu", "sas", "eurl", "sa", "sci", "snc", "scp", "scop", "ei", "gie", "ets"]
_LEGAL_RANK = {c: i for i, c in enumerate(_LEGAL_ORDER)}

# Generic words vendors append ("... Co Services", "... Inc Center"); they stay in core but let an
# EDGE legal token right before them be recognised.
_GENERIC_TAIL = frozenset(
    "services service center centre group partners enterprises trading authority board council "
    "association commission trust foundation society federation ventures industries solutions "
    "systems holdings international global associates".split())
_HONORIFICS = frozenset("the mr mrs ms dr smt shri sri messrs".split())
_EDGE_FILLERS = frozenset(["and"])

_ALIAS_RE = re.compile(
    r"\s+(?:f\s*/\s*k\s*/\s*a|fka|formerly\s+known\s+as|formerly|d\s*/\s*b\s*/\s*a|d\.b\.a\.?|dba"
    r"|doing\s+business\s+as|a\s*/\s*k\s*/\s*a|a\.k\.a\.?|aka|also\s+known\s+as|trading\s+as|t\s*/\s*a"
    r"|n[\u00e9]e)\s*:?\s+")  # 'née' only when accented: plain 'nee' is a common surname
_DOMAIN_RE = re.compile(r"^(?:https?://)?(?:www\.)?([a-z0-9][a-z0-9.\-]*?)\.(?:c[o0]m|co\.in|in|fr|net|org|biz|info)$")
_HANDLE_RE = re.compile(r"^[@#]([a-z0-9_.]{3,})$")
_ORDINAL_RE = re.compile(r"^\d+(?:st|nd|rd|th)$")
_LEET = str.maketrans({"0": "o", "1": "l", "3": "e", "4": "a", "5": "s", "6": "g", "7": "t", "8": "b"})
_LEET_DIGITS = frozenset("01345678")
_LEET_SHORT = {"c0": "co", "0f": "of", "t0": "to"}
_PLUS_AND_RE = re.compile(r"\s\+\s")   # 'Marshall + Perry' == 'Marshall & Perry'; 'V+ Select' untouched
_CODE_TOKEN_RE = re.compile(r"^\d+[a-z]$|^[a-z]\d+$")   # '68a', 'a206': house/unit codes, not leet
_NON_ALNUM_RE = re.compile(r"[^a-z0-9]")


def _deleet(tok: str) -> str:
    """Undo look-alike digit substitution in name tokens: '6yan'->'gyan', '50ftware'->'software',
    'c0rp'->'corp', 'l1c'->'llc', 'lnc'->'inc'. Leaves numbers, ordinals, 'b2b', 'a206', '68a'."""
    if tok.startswith("ln") and len(tok) > 2 and tok[2:].isalpha():
        return "i" + tok[1:]
    if tok.isalpha() or tok.isdigit() or not tok.isascii():
        return tok
    if tok in _LEET_SHORT:
        return _LEET_SHORT[tok]
    digits = [c for c in tok if c.isdigit()]
    letters = sum(c.isalpha() for c in tok)
    if (letters < 2 or len(digits) > 2 or not all(d in _LEET_DIGITS for d in digits)
            or not tok.isalnum() or _ORDINAL_RE.match(tok) or _CODE_TOKEN_RE.match(tok)):
        return tok
    return tok.translate(_LEET)


def _overlap(a: str, b: str) -> float:
    return sum((Counter(a) & Counter(b)).values()) / max(len(a), len(b))


def _fuzzy_legal_word(tok: str):
    """Scrambled 'private' / 'limited' ('Pivaet', 'Pricivate', 'Lmiietd'). Requires the first
    letter plus the word's distinctive letters so 'printers', 'pirates', 'limits' do not match."""
    if len(tok) < 5 or len(tok) > 10 or not tok.isalpha():
        return None
    if tok[0] == "p" and "v" in tok and _overlap(tok, "private") >= 0.7:
        return "private"
    if tok[0] == "l" and "m" in tok and "d" in tok and _overlap(tok, "limited") >= 0.7:
        return "limited"
    return None


def _extract_legal(tokens: list, table: dict):
    """Return (core_tokens, sorted canonical legal forms)."""
    n = len(tokens)
    if n == 0:
        return [], []
    info = [table.get(t) for t in tokens]
    # scrambled legal words: 'private' right before ltd/limited, 'limited' at the end or after pvt
    for i, t in enumerate(tokens):
        if info[i] is None and n > 1 and t[:1] in ("p", "l"):
            w = _fuzzy_legal_word(t)
            if w == "private" and i + 1 < n and info[i + 1] and info[i + 1][0] == "ltd":
                info[i] = table.get("private")
            elif w == "limited" and (i == n - 1 or (i > 0 and info[i - 1] and info[i - 1][0] == "pvt")):
                info[i] = table.get("limited")
    legal = [bool(x and x[1] == STRONG) for x in info]
    # 'private' anywhere once a ltd/limited is present ('Private Asian Transcripts Ltd')
    if any(x and x[0] == "ltd" and legal[i] for i, x in enumerate(info)):
        for i, x in enumerate(info):
            if x and x[1] == SUFFIX:
                legal[i] = True
    # PAIR ('public') only directly before ltd/limited
    for i, x in enumerate(info):
        if x and x[1] == PAIR and i + 1 < n and info[i + 1] and info[i + 1][0] == "ltd":
            legal[i] = True
    changed = True
    while changed:
        changed = False
        rest = [i for i in range(n) if not legal[i]]
        if len(rest) <= 1:
            break
        lo, hi = rest[0], rest[-1]
        x = info[lo]
        if x and x[1] == EDGE:
            legal[lo] = changed = True
            continue
        x = info[hi]
        if x and x[1] in (EDGE, SUFFIX):
            legal[hi] = changed = True
            continue
        # EDGE/SUFFIX token adjacent to an already-legal token ('Pvt Ltd', 'SAS Etablissements')
        for i in rest:
            x = info[i]
            if x and x[1] in (EDGE, SUFFIX) and ((i > 0 and legal[i - 1]) or (i + 1 < n and legal[i + 1])):
                legal[i] = changed = True
                break
        if changed:
            continue
        # EDGE/SUFFIX token right before a trailing generic word ('Associates Co Services')
        if len(rest) >= 3 and tokens[hi] in _GENERIC_TAIL:
            j = rest[-2]
            x = info[j]
            if x and x[1] in (EDGE, SUFFIX):
                legal[j] = changed = True
    core = [t for t, is_l in zip(tokens, legal) if not is_l]
    forms = sorted({info[i][0] for i in range(n) if legal[i]}, key=lambda c: _LEGAL_RANK.get(c, 99))
    if not core:  # name made only of legal words: keep them as core
        core = list(tokens)
    while len(core) > 1 and core[0] in _EDGE_FILLERS:
        core.pop(0)
    while len(core) > 1 and core[-1] in _EDGE_FILLERS:
        core.pop()
    return core, forms


def _name_segment(seg: str, table: dict):
    """Normalise one already fix_encoded + lower-cased name segment.
    Returns (core_tokens, legal_forms, is_domain_form, full_tokens)."""
    s = fold_accents(seg)
    s = _ID_RE.sub(" ", s)
    s = _PIPE_DOMAIN_TAIL_RE.sub("", s).strip()
    # domain / handle form: 'shylabrothersprivate.com', 'viprivate.c0m', '#BUSHSANTORO', '@rapidquality'
    m = _HANDLE_RE.match(s)
    if not m:
        s = _JUNK_EDGE_RE.sub("", s).strip()
        s = _PREFIX_RE.sub("", s).strip()
        s = _JUNK_EDGE_RE.sub("", s).strip()
        m = _DOMAIN_RE.match(s) if (s and " " not in s) else None
    if m:
        label = _deleet(_NON_ALNUM_RE.sub("", m.group(1)))
        if label:
            return [label], [], True, [label]
    s = _WWW_RE.sub("", s)
    s = _DOMAIN_SUFFIX_RE.sub("", s)
    s = _NULL_TOKEN_RE.sub(" ", s)
    s = _PLUS_AND_RE.sub(" and ", s).replace("&", " and ").replace("+", " ").replace("#", " ")
    toks = _dedupe_adjacent([_deleet(t) for t in _to_tokens(s)])
    while len(toks) > 1 and toks[0] in _HONORIFICS:
        toks.pop(0)
    if len(toks) > 2 and toks[0] == "m" and toks[1] == "s":  # 'M S' left from an unusual 'M/s'
        toks = toks[2:]
    core, legal = _extract_legal(toks, table)
    return core, legal, False, toks


@dataclass
class NameNorm:
    core: str = ""                      # legal form(s) removed, generic words kept
    legal: str = ""                     # canonical legal form(s): 'llc', 'pvt ltd', 'sarl ets', ''
    tokens: list = field(default_factory=list)
    spaceless: str = ""                 # core without spaces (char n-grams vs domain forms)
    alt_names: list = field(default_factory=list)   # cores of X and Y in 'X f/k/a Y' forms
    is_domain_form: bool = False        # 'duttainternationalschool.com', '#BUSHSANTORO'
    has_indic_script: bool = False
    full: str = ""                      # cleaned name including legal words


def transliterate_indic(s: str):
    """Stub: Indic-script -> Latin transliteration is provided by a later module."""
    return None


@lru_cache(maxsize=1 << 18)
def _normalize_name_cached(raw: str, ck: str):
    table = _LEGAL_BY_COUNTRY.get(ck, _LEGAL_DEFAULT)
    s = fix_encoding(raw).lower()
    has_indic = bool(_INDIC_RE.search(s))
    alts = ()
    m = _ALIAS_RE.search(s)
    if m:
        x, y = s[: m.start()], s[m.end():]
        cx, lx, dx, fx = _name_segment(x, table)
        cy, ly, dy, fy = _name_segment(y, table)
        if cx and cy:
            alts = tuple(dict.fromkeys([" ".join(cx), " ".join(cy)]))
            core, legal, dom, full = cy, (ly or lx), dy, fx + fy
            return (" ".join(core), " ".join(legal), tuple(core), alts, dom, has_indic, " ".join(full))
    core, legal, dom, full = _name_segment(s, table)
    return (" ".join(core), " ".join(legal), tuple(core), alts, dom, has_indic, " ".join(full))


def normalize_name(s: str, country: str = "") -> NameNorm:
    if not s:
        return NameNorm()
    core, legal, toks, alts, dom, indic, full = _normalize_name_cached(s, country_key(country))
    return NameNorm(core=core, legal=legal, tokens=list(toks), spaceless=core.replace(" ", ""),
                    alt_names=list(alts), is_domain_form=dom, has_indic_script=indic, full=full)


# ----------------------------------------------------------------------------------------------
# 7. Addresses: gazetteers (recognition only)
# ----------------------------------------------------------------------------------------------
_US_STATES = {
    "al": "alabama", "ak": "alaska", "az": "arizona", "ar": "arkansas", "ca": "california",
    "co": "colorado", "ct": "connecticut", "de": "delaware", "fl": "florida", "ga": "georgia",
    "hi": "hawaii", "id": "idaho", "il": "illinois", "in": "indiana", "ia": "iowa", "ks": "kansas",
    "ky": "kentucky", "la": "louisiana", "me": "maine", "md": "maryland", "ma": "massachusetts",
    "mi": "michigan", "mn": "minnesota", "ms": "mississippi", "mo": "missouri", "mt": "montana",
    "ne": "nebraska", "nv": "nevada", "nh": "new hampshire", "nj": "new jersey", "nm": "new mexico",
    "ny": "new york", "nc": "north carolina", "nd": "north dakota", "oh": "ohio", "ok": "oklahoma",
    "or": "oregon", "pa": "pennsylvania", "ri": "rhode island", "sc": "south carolina",
    "sd": "south dakota", "tn": "tennessee", "tx": "texas", "ut": "utah", "vt": "vermont",
    "va": "virginia", "wa": "washington", "wv": "west virginia", "wi": "wisconsin", "wy": "wyoming",
    "dc": "district of columbia",
}
US_STATE_ABBR = {v: k.upper() for k, v in _US_STATES.items()}   # full name -> 2-letter
_US_STATE_LOOKUP = {**_US_STATES, **{v: v for v in _US_STATES.values()},
                    "washington dc": "district of columbia", "washington d c": "district of columbia"}

_IN_STATE_CODES = {
    "tg": "telangana", "ts": "telangana", "ka": "karnataka", "mh": "maharashtra", "up": "uttar pradesh",
    "od": "odisha", "wb": "west bengal", "dl": "delhi", "hr": "haryana", "gj": "gujarat",
    "tn": "tamil nadu", "ap": "andhra pradesh", "mp": "madhya pradesh", "rj": "rajasthan", "pb": "punjab",
    "kl": "kerala", "br": "bihar", "jh": "jharkhand", "cg": "chhattisgarh", "ct": "chhattisgarh",
    "uk": "uttarakhand", "ut": "uttarakhand", "hp": "himachal pradesh", "as": "assam", "ga": "goa",
    "jk": "jammu and kashmir", "ch": "chandigarh", "py": "puducherry", "ar": "arunachal pradesh",
    "mn": "manipur", "ml": "meghalaya", "mz": "mizoram", "nl": "nagaland", "sk": "sikkim", "tr": "tripura",
    "la": "ladakh", "ld": "lakshadweep", "an": "andaman and nicobar islands",
    "dn": "dadra and nagar haveli and daman and diu", "dd": "dadra and nagar haveli and daman and diu",
}
IN_STATE_ABBR = {"telangana": "TG", "karnataka": "KA", "maharashtra": "MH", "uttar pradesh": "UP",
                 "odisha": "OD", "west bengal": "WB", "delhi": "DL", "haryana": "HR", "gujarat": "GJ",
                 "tamil nadu": "TN", "andhra pradesh": "AP", "madhya pradesh": "MP", "rajasthan": "RJ",
                 "punjab": "PB", "kerala": "KL", "bihar": "BR", "jharkhand": "JH", "chhattisgarh": "CG",
                 "uttarakhand": "UK", "himachal pradesh": "HP", "assam": "AS", "goa": "GA",
                 "jammu and kashmir": "JK", "chandigarh": "CH", "puducherry": "PY"}
_IN_STATE_NAMES = sorted(set(_IN_STATE_CODES.values()))
_IN_STATE_LEGACY = {
    "orissa": "odisha", "keralam": "kerala", "pondicherry": "puducherry", "uttaranchal": "uttarakhand",
    "nct of delhi": "delhi", "new delhi": None,  # new delhi is a city, never the state
    "jammu kashmir": "jammu and kashmir", "j and k": "jammu and kashmir", "tamilnadu": "tamil nadu",
    "chattisgarh": "chhattisgarh", "west bangal": "west bengal",
}
# Every Indic-script address part found in S2/S3/T2/T3 (DuckDB scan, 2026-09-25): all state names.
_IN_STATE_INDIC_RAW = {
    "महाराष्ट्र": "maharashtra", "दिल्ली": "delhi", "उत्तर प्रदेश": "uttar pradesh", "ಕರ್ನಾಟಕ": "karnataka",
    "தமிழ்நாடு": "tamil nadu", "পশ্চিমবঙ্গ": "west bengal", "ગુજરાત": "gujarat", "తెలంగాణ": "telangana",
    "हरियाणा": "haryana", "राजस्थान": "rajasthan", "കേരളം": "kerala", "बिहार": "bihar",
    "मध्य प्रदेश": "madhya pradesh", "ఆంధ్రప్రదేశ్": "andhra pradesh", "ਪੰਜਾਬ": "punjab", "ଓଡ଼ିଶା": "odisha",
    # a few extra spellings that are cheap to cover
    "ओडिशा": "odisha", "पंजाब": "punjab", "गुजरात": "gujarat", "कर्नाटक": "karnataka", "तमिलनाडु": "tamil nadu",
    "तेलंगाना": "telangana", "केरल": "kerala", "पश्चिम बंगाल": "west bengal", "झारखंड": "jharkhand",
    "छत्तीसगढ़": "chhattisgarh", "उत्तराखंड": "uttarakhand", "असम": "assam", "गोवा": "goa",
    "ആന്ധ്രാപ്രദേശ്": "andhra pradesh", "ఆంధ్ర ప్రదేశ్": "andhra pradesh",
}
_IN_STATE_LOOKUP = {**_IN_STATE_CODES, **{v: v for v in _IN_STATE_NAMES},
                    **{k: v for k, v in _IN_STATE_LEGACY.items() if v},
                    **{" ".join(_prep(k).split()): v for k, v in _IN_STATE_INDIC_RAW.items()}}

_FR_REGIONS = [
    "auvergne rhone alpes", "bourgogne franche comte", "bretagne", "centre val de loire", "corse",
    "grand est", "hauts de france", "ile de france", "normandie", "nouvelle aquitaine", "occitanie",
    "pays de la loire", "provence alpes cote dazur", "guadeloupe", "martinique", "guyane",
    "la reunion", "mayotte",
]
_FR_STATE_LOOKUP = {r: r for r in _FR_REGIONS}
_FR_STATE_LOOKUP.update({"paca": "provence alpes cote dazur", "reunion": "la reunion",
                         "pays de loire": "pays de la loire", "idf": "ile de france"})
# Départements: recognised so they are not mistaken for the city; NOT mapped to régions.
_FR_DEPARTEMENTS = frozenset("""
ain|aisne|allier|alpes de haute provence|hautes alpes|alpes maritimes|ardeche|ardennes|ariege|aube|
aude|aveyron|bouches du rhone|calvados|cantal|charente|charente maritime|cher|correze|corse du sud|
haute corse|cote dor|cotes darmor|creuse|dordogne|doubs|drome|eure|eure et loir|finistere|gard|
haute garonne|gers|gironde|herault|ille et vilaine|indre|indre et loire|isere|jura|landes|
loir et cher|loire|haute loire|loire atlantique|loiret|lot|lot et garonne|lozere|maine et loire|
manche|marne|haute marne|mayenne|meurthe et moselle|meuse|morbihan|moselle|nievre|nord|oise|orne|
pas de calais|puy de dome|pyrenees atlantiques|hautes pyrenees|pyrenees orientales|bas rhin|
haut rhin|rhone|haute saone|saone et loire|sarthe|savoie|haute savoie|seine maritime|seine et marne|
yvelines|deux sevres|somme|tarn|tarn et garonne|var|vaucluse|vendee|vienne|haute vienne|vosges|yonne|
territoire de belfort|essonne|hauts de seine|seine saint denis|val de marne|val doise
""".replace("\n", "").split("|"))

# ----------------------------------------------------------------------------------------------
# 8. Addresses: abbreviation maps per country
# ----------------------------------------------------------------------------------------------
_ABBR_COMMON = {
    "rd": "road", "ave": "avenue", "av": "avenue", "avn": "avenue", "ln": "lane", "blvd": "boulevard",
    "ct": "court", "cir": "circle", "ter": "terrace", "terr": "terrace", "pl": "place", "hwy": "highway",
    "pkwy": "parkway", "trl": "trail", "sq": "square", "pt": "point", "mt": "mount", "ft": "fort",
    "n": "north", "s": "south", "e": "east", "w": "west",
    "ne": "northeast", "nw": "northwest", "se": "southeast", "sw": "southwest",
    "apt": "apartment", "apts": "apartment", "apartments": "apartment", "appartment": "apartment",
    "bldg": "building", "fl": "floor", "flr": "floor", "rte": "route", "hts": "heights",
    "twp": "township", "expy": "expressway", "fwy": "freeway", "ctr": "center", "rm": "room",
}
_ABBR_INDIA_EXTRA = {
    "sec": "sector", "ph": "phase", "blk": "block", "opp": "opposite", "nr": "near", "soc": "society",
    "socy": "society", "ngr": "nagar", "clny": "colony", "extn": "extension", "ext": "extension",
    "vill": "village", "vil": "village", "dist": "district", "distt": "district", "bhd": "behind",
    "grd": "ground", "gnd": "ground", "teh": "tehsil",
    # legacy -> current names
    "bangalore": "bengaluru", "bombay": "mumbai", "madras": "chennai", "calcutta": "kolkata",
    "gurgaon": "gurugram", "poona": "pune", "orissa": "odisha", "baroda": "vadodara", "mysore": "mysuru",
    "mangalore": "mangaluru", "cochin": "kochi", "trivandrum": "thiruvananthapuram",
    "pondicherry": "puducherry", "keralam": "kerala", "uttaranchal": "uttarakhand", "benares": "varanasi",
    "allahabad": "prayagraj", "ahmadabad": "ahmedabad", "vizag": "visakhapatnam",
    "vishakhapatnam": "visakhapatnam", "vishakapatnam": "visakhapatnam", "simla": "shimla",
    "gulbarga": "kalaburagi", "belgaum": "belagavi", "hubli": "hubballi",
}
_ABBR_FRANCE = {
    "r": "rue", "av": "avenue", "ave": "avenue", "avn": "avenue", "bd": "boulevard", "bld": "boulevard",
    "blvd": "boulevard", "bvd": "boulevard", "pl": "place", "imp": "impasse", "ch": "chemin",
    "chem": "chemin", "che": "chemin", "all": "allee", "rte": "route", "sq": "square", "qu": "quai",
    "q": "quai", "crs": "cours", "st": "saint", "ste": "sainte", "fg": "faubourg", "fbg": "faubourg",
    "res": "residence", "resid": "residence", "appt": "appartement", "apt": "appartement",
    "bat": "batiment", "pass": "passage", "sent": "sentier", "prom": "promenade", "pte": "porte",
    "gal": "general", "gen": "general", "mal": "marechal", "pdt": "president", "dr": "docteur",
    "prof": "professeur", "rpt": "rond point",
}
_UNIT_WORDS = frozenset("unit apt apartment suite ste bldg building floor fl flr room rm appt "
                        "appartement etage batiment bat".split())
_STREET_TYPES = frozenset(
    "road street avenue drive lane boulevard court circle terrace place highway parkway trail square "
    "way loop run pike row walk path alley crossing cove bend marg rue allee impasse chemin route quai "
    "cours passage sentier promenade".split())
_NULL_PARTS = frozenset(["null", "n a", "na", "none", "nil", "nan", "not available", "unknown"])

_COUNTRY_CFG = {
    # state_code_first: when several parts look like a state, a 2-letter code beats a full name
    # (US cities named Washington / Delaware / Indiana ...). India prefers full names because a
    # stray fragment ('Flo, Or') can look like a code.
    "us": {"abbr": _ABBR_COMMON, "states": _US_STATE_LOOKUP, "districts": frozenset(),
           "st_rule": True, "saint_street": True, "drop_after_number": frozenset(),
           "state_code_first": True, "city_suffix_noise": True},
    "india": {"abbr": {**_ABBR_COMMON, **_ABBR_INDIA_EXTRA}, "states": _IN_STATE_LOOKUP,
              "districts": frozenset(), "st_rule": True, "saint_street": True,
              "drop_after_number": frozenset(), "state_code_first": False, "city_suffix_noise": False},
    "france": {"abbr": _ABBR_FRANCE, "states": _FR_STATE_LOOKUP, "districts": _FR_DEPARTEMENTS,
               "st_rule": False, "saint_street": False,
               "drop_after_number": frozenset(["bis", "ter", "quater", "b"]),
               "state_code_first": False, "city_suffix_noise": False},
}
_CFG_DEFAULT = {"abbr": _ABBR_COMMON, "states": {}, "districts": frozenset(), "st_rule": True,
                "saint_street": False, "drop_after_number": frozenset(), "state_code_first": False,
                "city_suffix_noise": False}
_CITY_TYPOS = frozenset(["cty", "ciy", "citty", "ctiy", "cit", "ctiy"])
_CDP_RE = re.compile(r"^[a-z]?c?cdp$")


def _strip_city_noise(toks: tuple) -> tuple:
    """US vendor noise on the city part: '... CDP', '... CCDP', 'PHOENIXCDP', '... CTIY', and an
    appended 'City' ('Granite City' vs 'Granite'); trailing city/cdp are dropped on both sides."""
    toks = list(toks)
    if toks and len(toks[-1]) > 5 and toks[-1].endswith("cdp"):
        toks[-1] = toks[-1][:-3]
    while len(toks) > 1 and (_CDP_RE.match(toks[-1]) or toks[-1] in _CITY_TYPOS or toks[-1] == "city"):
        toks.pop()
    return tuple(toks)

# ----------------------------------------------------------------------------------------------
# 9. Address part processing
# ----------------------------------------------------------------------------------------------
_PO_BOX_RE = re.compile(r"\b(?:p\s*\.?\s*o\s*\.?\s*box|post\s+box|postbox|pmb)\b\s*[#:.-]?\s*\d*")
_HASH_NUM_RE = re.compile(r"#+(?=\s*\d)")
_FUSED_NO_RE = re.compile(r"^(no|nos|hno|hn|dno)[-/.:]?(?=\d)")
_NUMISH_RE = re.compile(r"^[a-z]{0,2}[-/]?\d")
_NUM_SUFFIX_RE = re.compile(r"^(\d+)(bis|ter|quater|b)$")
_PREFIX_HEADS = frozenset("h house plot door shop flat office off".split())
_NO_WORDS = frozenset(["no", "nos", "number", "num"])
_FUSED_PREFIX_WORDS = frozenset(["hno", "hn", "dno"])


def _numish(tok: str) -> bool:
    return bool(_NUMISH_RE.match(tok))


def _strip_zeros(d: str) -> str:
    return d.lstrip("0") or "0"


def _base_part_tokens(part: str, drop_after_number: frozenset) -> list:
    """Tokens of one comma-part, before abbreviation expansion: '#', 'no', 'h.no', 'plot no'...
    prefixes removed, ordinals/leading zeros normalised, '1/2' dropped, null dropped."""
    s = _PO_BOX_RE.sub(" ", part)
    s = _HASH_NUM_RE.sub("", s)
    s = _NULL_TOKEN_RE.sub(" ", s)
    s = s.replace("&", " and ").replace("#", " ")
    raw = _dedupe_adjacent(_to_tokens(s))
    toks = []
    for t in raw:
        m = _FUSED_NO_RE.match(t)
        if m:  # 'no10' -> 'no', '10';  'hno-40' -> 'hno', '40'
            toks.append(m.group(1))
            t = t[m.end():].lstrip("-/.:")
        if t.isdigit():
            t = _strip_zeros(t)
        elif _ORDINAL_RE.match(t):
            t = _strip_zeros(re.match(r"\d+", t).group())
        elif drop_after_number:
            m2 = _NUM_SUFFIX_RE.match(t)
            if m2:
                t = _strip_zeros(m2.group(1))
        if t and t != "1/2":
            toks.append(t)
    # prefix phrases before a number: 'h no 677', 'plot no 5', 'flat 102', 'no 516', 'hno 40'
    out = []
    i, n = 0, len(toks)
    while i < n:
        t = toks[i]
        nxt = toks[i + 1] if i + 1 < n else ""
        nxt2 = toks[i + 2] if i + 2 < n else ""
        if t in _PREFIX_HEADS and nxt in _NO_WORDS and _numish(nxt2):
            i += 2
            continue
        if t in _PREFIX_HEADS and t not in ("h", "off") and _numish(nxt):
            i += 1
            continue
        if (t in _NO_WORDS or t in _FUSED_PREFIX_WORDS) and _numish(nxt):
            i += 1
            continue
        if drop_after_number and t in drop_after_number and out and out[-1][:1].isdigit():
            i += 1
            continue
        out.append(t)
        i += 1
    return out


def _expand_tokens(toks: list, cfg: dict) -> list:
    abbr = cfg["abbr"]
    n = len(toks)
    out = []
    for i, t in enumerate(toks):
        nxt = toks[i + 1] if i + 1 < n else ""
        if cfg["st_rule"] and t == "st":
            # 'st' = saint before a word ('st louis', '5 st andrews rd'), street otherwise
            t = "saint" if (nxt and nxt[0].isalpha() and nxt not in _UNIT_WORDS) else "street"
        elif cfg["st_rule"] and t == "dr":
            t = "drive" if (not nxt or _numish(nxt)) else "dr"
        elif cfg["st_rule"] and t == "ste":
            t = "suite" if _numish(nxt) else "ste"
        elif cfg["saint_street"] and t == "saint" and i == n - 1 and i >= 2 and _numish(toks[0]):
            t = "street"  # vendor noise: '3315 FREMONT SAINT' for 'Fremont Street'
        else:
            t = abbr.get(t, t)
        out.extend(t.split())
    return out


# part classes
P_STREET, P_UNIT, P_OTHER, P_DISTRICT, P_STATE, P_NUMERIC = "street", "unit", "other", "district", "state", "numeric"


@lru_cache(maxsize=1 << 18)
def _process_part(part: str, ck: str):
    """-> (tokens tuple, state canonical or '', district or '', is_null, starts_numish, all_numeric,
    first_is_unit, last_is_street_type)"""
    cfg = _COUNTRY_CFG.get(ck, _CFG_DEFAULT)
    base = _base_part_tokens(part, cfg["drop_after_number"])
    if not base:
        return ((), "", "", True, False, False, False, False, 0)
    joined = " ".join(base)
    if joined in _NULL_PARTS:
        return ((), "", "", True, False, False, False, False, 0)
    state = cfg["states"].get(joined, "")
    district = joined if (not state and joined in cfg["districts"]) else ""
    toks = tuple(_expand_tokens(base, cfg))
    if state:
        toks = tuple(state.split())
        is_code = len(joined) <= 2 or joined == "district of columbia"
        state_prio = 2 if is_code == cfg["state_code_first"] else 1
    else:
        state_prio = 0
    first = base[0]
    starts_num = _numish(first) or (len(first) == 1 and first.isalpha() and len(base) > 1 and _numish(base[1]))
    all_num = all(_HAS_DIGIT_RE.search(t) for t in base)
    if cfg["city_suffix_noise"] and not state and not starts_num:
        toks = _strip_city_noise(toks)
    return (toks, state, district, False, starts_num, all_num,
            first in _UNIT_WORDS,
            len(toks) > 1 and (toks[-1] in _STREET_TYPES or toks[0] in _STREET_TYPES),  # 'Main St' / 'Rue X'
            state_prio)


def _first_number(tokens) -> str:
    """Street number from the first number-ish token (a leading single letter may precede it)."""
    for tok in tokens[:2]:
        if _numish(tok):
            m = _DIGITS_RE.search(tok)
            return _strip_zeros(m.group()) if m else ""
    return ""


_DISTRICT_LIKE_RE = re.compile(
    r"(?:^| )(?:city|urban|rural|district|dist|distt)$"
    r"|^(?:north|south|east|west|central)(?: (?:north|south|east|west))? \S")


def _pick_city(localities: list) -> str:
    """Last locality part, skipping parts with digits and district-like parts ('Mumbai City',
    'Bangalore Urban', 'South West Delhi') when an alternative exists. On 60k GT pairs this matches
    the S1 city in 67% of India pairs (plain 'last part': 60%) and 83% of US pairs (unchanged)."""
    if not localities:
        return ""
    cands = [p for p in localities if not _HAS_DIGIT_RE.search(p)] or localities
    cands = [p for p in cands if not _DISTRICT_LIKE_RE.search(p)] or cands
    return cands[-1]


@dataclass
class AddrNorm:
    tokens: list = field(default_factory=list)     # canonical tokens, canonical part order
    numbers: list = field(default_factory=list)    # digit runs, leading zeros stripped, deduped
    street_number: str = ""
    city: str = ""
    state: str = ""                                # canonical full state / région name
    postal: str = ""                               # always '' in this data
    parts: list = field(default_factory=list)      # cleaned comma parts, original order
    district: str = ""                             # recognised département (France) or ''
    localities: list = field(default_factory=list) # all 'other' parts (city candidates)
    street: str = ""                               # street part without its leading number


def normalize_address(s: str, country: str = "") -> AddrNorm:
    if not s:
        return AddrNorm()
    ck = country_key(country)
    text = _prep(s)
    raw_parts = re.split(r"[,;]", text)
    procs = []
    for rp in raw_parts:
        rp = rp.strip()
        if not rp:
            continue
        pr = _process_part(rp, ck)
        if pr[3]:  # null / empty part
            continue
        procs.append(pr)
    if not procs:
        return AddrNorm()

    # state: highest-priority recognised state part, last one on ties; district: last one
    state_idx = max((i for i, p in enumerate(procs) if p[1]), key=lambda i: (procs[i][8], i), default=-1)
    district_idx = max((i for i, p in enumerate(procs) if p[2]), default=-1)
    classes = []
    street_found = False
    for i, p in enumerate(procs):
        if i == state_idx:
            c = P_STATE
        elif i == district_idx:
            c = P_DISTRICT
        elif p[5] and street_found:
            c = P_NUMERIC        # e.g. a bare '75182' after the street part
        elif p[4]:
            c = P_STREET
            street_found = True
        elif p[6]:
            c = P_UNIT
        else:
            c = P_OTHER
        classes.append(c)
    if not street_found:  # no number: first part starting/ending with a street type ('Kenforest Drive', 'Rue Darras')
        for i, p in enumerate(procs):
            if classes[i] == P_OTHER and p[7]:
                classes[i] = P_STREET
                break

    order = {P_STREET: 0, P_UNIT: 1, P_NUMERIC: 2, P_OTHER: 3, P_DISTRICT: 4, P_STATE: 5}
    idx_sorted = sorted(range(len(procs)), key=lambda i: (order[classes[i]], i))
    tokens = [t for i in idx_sorted for t in procs[i][0]]

    numbers = []
    seen = set()
    for i in idx_sorted:
        if classes[i] == P_STATE:
            continue
        for t in procs[i][0]:
            if _HAS_DIGIT_RE.search(t):
                for d in _DIGITS_RE.findall(t):
                    d = _strip_zeros(d)
                    if d not in seen:
                        seen.add(d)
                        numbers.append(d)

    street_number, street = "", ""
    street_parts = [i for i in range(len(procs)) if classes[i] == P_STREET]
    if street_parts:
        st_toks = procs[street_parts[0]][0]
        if procs[street_parts[0]][4]:
            street_number = _first_number(st_toks)
        street = " ".join(t for t in st_toks if not _HAS_DIGIT_RE.search(t) and not (len(t) == 1 and t.isalpha()))

    localities = [" ".join(procs[i][0]) for i in range(len(procs)) if classes[i] == P_OTHER]
    city = _pick_city(localities)
    return AddrNorm(
        tokens=tokens,
        numbers=numbers,
        street_number=street_number,
        city=city,
        state=procs[state_idx][1] if state_idx >= 0 else "",
        postal="",
        parts=[" ".join(p[0]) for p in procs],
        district=procs[district_idx][2] if district_idx >= 0 else "",
        localities=localities,
        street=street,
    )


# ----------------------------------------------------------------------------------------------
# 10. Record-level helpers and blocking keys
# ----------------------------------------------------------------------------------------------
_GENERIC_NAME_WORDS = frozenset(
    "and of the india care associates group center centre partners services service health clinic "
    "company medical dental family medicine consulting solutions systems international global "
    "enterprises trading industries holdings ventures club ecole maison association amicale comite "
    "union federation societe france de la le les du des et private limited llc inc ltd pvt".split())


def _rarest_token(tokens, token_df=None) -> str:
    cands = [t for t in tokens if len(t) >= 3 and not t.isdigit()]
    if not cands:
        return ""
    if token_df is not None:
        return min(cands, key=lambda t: (token_df.get(t, 0), -len(t)))
    specific = [t for t in cands if t not in _GENERIC_NAME_WORDS] or cands
    return max(specific, key=len)


def blocking_keys(name: NameNorm, addr: AddrNorm = None, country: str = "", token_df=None) -> list:
    """Cheap blocking keys (strings, prefixed by country key):
    ns = spaceless name core (plus spaceless alt names), f2 = first two core tokens,
    cs = (city, street_number), cr = (city, rarest-looking name token; lowest df if token_df given)."""
    ck = country_key(country)
    keys = []
    if name.spaceless:
        keys.append(f"{ck}|ns|{name.spaceless}")
    for alt in name.alt_names:
        keys.append(f"{ck}|ns|{alt.replace(' ', '')}")
    if len(name.tokens) >= 2:
        keys.append(f"{ck}|f2|{name.tokens[0]} {name.tokens[1]}")
    if addr is not None and addr.city:
        if addr.street_number:
            keys.append(f"{ck}|cs|{addr.city}|{addr.street_number}")
        rare = _rarest_token(name.tokens, token_df)
        if rare:
            keys.append(f"{ck}|cr|{addr.city}|{rare}")
    return list(dict.fromkeys(keys))


def normalize_record(name: str, address: str, country: str) -> dict:
    """Flat dict: name_* and addr_* fields plus 'country' key and 'blocking_keys'."""
    nn = normalize_name(name, country)
    an = normalize_address(address, country)
    rec = {"country": country_key(country)}
    rec.update({f"name_{k}": v for k, v in vars(nn).items()})
    rec.update({f"addr_{k}": v for k, v in vars(an).items()})
    rec["blocking_keys"] = blocking_keys(nn, an, country)
    return rec


def blocking_normalizer(df):
    """Adapter for ``src.blocking --normalizer src.normalize:blocking_normalizer``: takes a polars
    DataFrame (entity_id, business_name, business_address, country) and adds name_n (core),
    name_ns (spaceless core) and addr_n (canonical address tokens). polars is imported lazily so
    this module itself stays stdlib-only."""
    import polars as pl  # noqa: WPS433 (optional dependency, only for this adapter)

    names = df["business_name"].to_list()
    addrs = df["business_address"].to_list()
    ctry = df["country"].to_list()
    name_n, name_ns, addr_n = [], [], []
    for n, a, c in zip(names, addrs, ctry):
        nn = normalize_name(n or "", c or "")
        an = normalize_address(a or "", c or "")
        name_n.append(nn.core)
        name_ns.append(nn.spaceless)
        addr_n.append(" ".join(an.tokens))
    return df.with_columns(pl.Series("name_n", name_n, dtype=pl.Utf8),
                           pl.Series("name_ns", name_ns, dtype=pl.Utf8),
                           pl.Series("addr_n", addr_n, dtype=pl.Utf8))