File size: 31,221 Bytes
b5cbcc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""日本語Web文書向けのPII検出・置換器。

``PII_detect.md`` の検出方針を踏まえ、正規表現・チェックデジットに加えて
SudachiPy(形態素解析、人名辞書付き)で自然文中の氏名を検出する。学習済み
NER(GLiNER-ja)は全件処理には重いため ``pii_residual_check.py`` の残存確認に
使う。公開用データでは、検出した値を削除するのではなく、種別ごとの
プレースホルダーへ置換する。対象は次の7種類に限定する。

* 電話番号
* メールアドレス
* 番地レベルの住所
* 個人名と所属の組合せ
* マイナンバー
* クレジットカード番号
* 銀行口座番号

郵便番号だけ、IPアドレス、秘密情報、生年月日などは対象外とする。個人名
だけは「氏名:」等のラベル文脈に限って置換する。番号系(マイナンバー、
カード、口座)はURLでは検出せず、本文でもラベル文脈か区切り書式を必須にする
(無作為な数字列の1割はチェックデジットを通るため)。将来 fuseji、GLiNER-ja、GiNZA 等を追加する場合は
``PIIDetector`` の結果へ検出結果を追加できる。
"""

from __future__ import annotations

import re
import unicodedata
from dataclasses import dataclass
from typing import Any, Iterable


PII_LABELS_JA = {
    "email": "メールアドレス",
    "phone": "電話番号",
    "address": "番地レベルの住所",
    "person_affiliation": "個人名+所属",
    "person_name": "個人名",
    "my_number": "マイナンバー",
    "credit_card": "クレジットカード番号",
    "bank_account": "銀行口座番号",
}

PLACEHOLDERS = {
    "email": "<EMAIL>",
    "phone": "<PHONE>",
    "address": "<ADDRESS>",
    "person_affiliation": "<PERSON_AFFILIATION>",
    "person_name": "<PERSON_NAME>",
    "my_number": "<MY_NUMBER>",
    "credit_card": "<CREDIT_CARD>",
    "bank_account": "<BANK_ACCOUNT>",
}

TARGET_PII_TYPES = tuple(PII_LABELS_JA)


@dataclass(frozen=True)
class PIIMatch:
    """検出されたPIIの位置と監査用メタデータ。位置はNFKC後の文字列基準。"""

    pii_type: str
    field: str
    start: int
    end: int
    value: str
    method: str
    confidence: str = "high"

    @property
    def label_ja(self) -> str:
        return PII_LABELS_JA.get(self.pii_type, self.pii_type)

    @property
    def masked_value(self) -> str:
        return mask_value(self.pii_type, self.value)

    @property
    def placeholder(self) -> str:
        return PLACEHOLDERS.get(self.pii_type, "<PII>")

    def to_dict(self) -> dict[str, Any]:
        return {
            "pii_type": self.pii_type,
            "pii_type_ja": self.label_ja,
            "field": self.field,
            "start": self.start,
            "end": self.end,
            "matched_value_masked": self.masked_value,
            "method": self.method,
            "confidence": self.confidence,
            "placeholder": self.placeholder,
        }


def normalize_text(value: Any) -> str:
    """全角・半角差を吸収して照合する。"""

    if value is None:
        return ""
    return unicodedata.normalize("NFKC", str(value))


def mask_value(pii_type: str, value: str) -> str:
    """監査JSONにPIIそのものを再掲しないためのマスキング。"""

    if not value:
        return ""
    if pii_type == "email" and "@" in value:
        local, domain = value.split("@", 1)
        masked_local = local[0] + "*" * max(1, len(local) - 2) + local[-1:]
        return f"{masked_local}@{domain}"
    if pii_type in {"phone", "my_number", "credit_card", "bank_account"}:
        chars = list(value)
        positions = [i for i, char in enumerate(chars) if char.isalnum()]
        keep = 4
        for index in positions[:-keep]:
            chars[index] = "*"
        return "".join(chars)
    if pii_type == "address":
        return value[:3] + "***"
    if pii_type == "person_affiliation":
        return "***"
    return "***"


def is_valid_luhn(value: str) -> bool:
    digits = [int(char) for char in value if char.isdigit()]
    if len(digits) < 13 or len(digits) > 19:
        return False
    checksum = 0
    parity = len(digits) % 2
    for index, digit in enumerate(digits):
        if index % 2 == parity:
            digit *= 2
            if digit > 9:
                digit -= 9
        checksum += digit
    return checksum % 10 == 0


def is_valid_mynumber(value: str) -> bool:
    """12桁の個人番号のチェックデジットを検証する。"""

    digits = [int(char) for char in value if char.isdigit()]
    if len(digits) != 12:
        return False
    # 左から11桁に対して、右から 2,3,4,5,6,7 を繰り返す。
    weights = [2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6]
    total = sum(digit * weight for digit, weight in zip(reversed(digits[:11]), weights))
    check_digit = (11 - (total % 11)) % 10
    return check_digit == digits[-1]


EMAIL_RE = re.compile(
    r"(?<![A-Za-z0-9._%+\-])([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)(?![A-Za-z0-9._%+\-])"
)
PHONE_SEPARATED_RE = re.compile(
    # 改行を区切りに含めない。住所末尾の番地と次行の電話番号を
    # ひとつの不正な候補として連結しないため、空白は半角スペース・タブのみ。
    # 先行する郵便番号・日付などが不正候補になっても、後続の電話番号の
    # 開始位置を検査できるよう、候補全体を先読みして重複開始を許可する。
    r"(?<!\d)(?=(?P<value>(?:\+81[ \t-]?)?0?\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{1,4}(?:[ \t]?-[ \t]?|[ \t])\d{3,4})(?!\d))"
)
PHONE_MOBILE_RE = re.compile(r"(?<!\d)0[789]0\d{8}(?!\d)")
PHONE_PLAIN_RE = re.compile(
    r"(?<!\d)(?:0120\d{6}|0570\d{6}|050\d{8}|0[1-9]\d{8})(?!\d)"
)
PHONE_CONTEXT_RE = re.compile(
    # ラベル候補も先読みして、TELの後に別のFAXが続く場合などの
    # 後続ラベルを取りこぼさない。
    r"(?=(?:電話|携帯|連絡先|tel|telephone|phone|fax|ファクシミリ|ファックス)\s*[::]?[^0-9+]{0,10}(?P<value>\+?\d[\d\s().-]{8,18}\d))",
    re.IGNORECASE,
)
# 12桁(4-4-4区切りも可)。チェックデジットに加えて、ラベル文脈を必須にする。
# 無作為な12桁の1割はチェックデジットを通るため、URL中のIDや注文番号を誤検出しないため。
MY_NUMBER_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]?\d{4}[ -]?\d{4})(?![\d-])")
MY_NUMBER_CONTEXT_RE = re.compile(r"(?:個人番号|マイナンバー|my\s*number)", re.IGNORECASE)
# 13〜19桁。区切り書式(4-4-4-4、4-6-5 等)かラベル文脈を必須にする(Luhn だけでは1割が通る)。
CARD_RE = re.compile(r"(?<![\d-])(?:\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{1,7}|\d{4}[ -]\d{6}[ -]\d{5}|\d{13,19})(?![\d-])")
CARD_CONTEXT_RE = re.compile(
    r"(?:カード番号|クレジットカード|クレカ|card\s*(?:no\.?|number)|credit\s*card|visa|master\s*card|jcb|amex|american\s*express|diners)",
    re.IGNORECASE,
)
# 直前にこれらのラベルがある数字列は注文・伝票等の番号とみなして除外する。
NUMBER_NEGATIVE_CONTEXT_RE = re.compile(
    r"(?:注文番号|受注番号|伝票番号|追跡番号|お問い?合わせ番号|受付番号|管理番号|会員番号|予約番号|商品番号|型番|isbn|jan|tracking|order\s*(?:no\.?|number))",
    re.IGNORECASE,
)

# 都道府県・市区町村に続く番地(1-2-3、1丁目2番3号等)を必須にする。番地の後ろの
# 建物名・部屋番号も住所の一部として取り込む(「<ADDRESS>-802」のような取り残しを防ぐ)。
# 番地: 算用数字と漢数字の両方、「1-2-3」「1丁目2番3号」「一丁目二番三号」「1丁目2-3」「1ー2ー3」を許容
_NUM = r"[0-9一二三四五六七八九十〇零]+"
# 区切り記号(-、-、‐、ー)の前後には OCR・Web抽出由来の空白を1つまで許す。
_SEP = r"\s?[--‐ー]\s?"
_ADDRESS_BLOCK = (
    rf"(?:{_NUM}\s?丁目\s?{_NUM}(?:\s?番(?:地)?\s?(?:{_NUM}\s?号?)?|{_SEP}{_NUM}(?:{_SEP}{_NUM})?)"
    rf"|{_NUM}(?:{_SEP}{_NUM}){{1,3}}(?:番地?)?"
    rf"|{_NUM}\s?番地?(?:\s?{_NUM}\s?号)?)"
)
_ADDRESS_TAIL = (
    r"(?:\s*[^\s,、。\n()()]{0,20}?(?:ビル|マンション|ハイツ|コーポ|レジデンス|アパート|タワー|ハウス|荘|寮|号館)[^\s,、。\n()()]{0,10})?"
    r"(?:\s*\d{1,4}\s*(?:号室|号|[Ff]|階))?"
)
# 都道府県から始まる住所。改行・空白の混入(Web抽出やOCR)を許すため、区切りは句読点のみとする。
ADDRESS_RE = re.compile(
    r"(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県)[^,、。]{1,60}?(?:市|区|町|村)[^,、。]{0,35}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
)
# 都道府県が省かれた「福岡市博多区博多駅前1-2-3」「宇都宮市江野町1-15」。市・区の後に町名相当を1文字以上要求する。
ADDRESS_CITY_RE = re.compile(
    r"(?P<value>(?<![都京大])[一-龥々ぁ-ゖ]{1,6}(?:市|区|郡)[一-龥々ぁ-ゖァ-ヶー0-9\s]{1,30}?(?:町|村|区|丁目|[一-龥々]{1,6})" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
)
# ラベル付きの住所は、都道府県が省かれた「宇都宮市江野町1-15」の形も許可する(残存確認で発見した取りこぼし)。
ADDRESS_CONTEXT_RE = re.compile(
    r"(?:住所|所在地|送付先|配送先)\s*[::]?\s*(?P<value>(?:北海道|東京都|大阪府|京都府|[一-龥々]{2,3}県|[一-龥々ぁ-ゖァ-ヶー]{1,6}(?:市|区|郡))[^。,、]{1,80}?" + _ADDRESS_BLOCK + _ADDRESS_TAIL + r")"
)

# 氏名: 漢字2〜6字、または漢字1〜3字+かな2〜6字(佐藤ゆかり)。「皆さん」のような1字+さんは拾わない。
_NAME = r"(?:[一-龥々]{2,6}|[一-龥々]{1,3}\s?[ぁ-ゖァ-ヶー]{2,6})"
# 所属: 法人格で始まる名称、または組織を示す語尾で終わる名称(20字以内)。任意で部署。
_ORG_PREFIX = r"(?:株式会社|有限会社|合同会社|合資会社|一般社団法人|一般財団法人|公益社団法人|公益財団法人|[Nn][Pp][Oo]法人|学校法人|医療法人|社会福祉法人|独立行政法人|国立研究開発法人)"
_ORG_SUFFIX = r"(?:株式会社|有限会社|合同会社|会社|大学院|大学|高等学校|高校|中学校|小学校|専門学校|病院|クリニック|医院|省|庁|県庁|市役所|区役所|町役場|村役場|銀行|信用金庫|研究所|研究センター|協会|連盟|組合|法律事務所|事務所|事務局|財団|法人|商工会議所|観光局|放送局|新聞社|出版社)"
_ORG = rf"(?:{_ORG_PREFIX}[^\s。、,,()()]{{1,20}}|[^\s。、,,()()のがはをにでと]{{1,20}}?{_ORG_SUFFIX})"
_ORG_RE = re.compile(_ORG)
_DEPT = r"(?:\s*[^\s。、,,()()]{0,15}?(?:部|課|室|科|係|チーム|支店|支社|営業所|研究室))?"
# 所属の後ろに続く役職(「株式会社ABC 代表」「○○会 会員」)も置換範囲に含める。
_TITLE_OPT = r"(?:\s*[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士|職員|会員|理事|社員|員))?"
_TITLE = r"(?:[^\s。、,,()()の]{0,8}?(?:長|社長|部長|課長|主任|教授|准教授|講師|代表|取締役|[Cc][Ee][Oo]|[Cc][Tt][Oo]|マネージャー|リーダー|担当|研究員|弁護士))"
# 「氏名:山田太郎(株式会社ABC)」「担当者:山田太郎、株式会社ABC 営業部」
NAME_AFFILIATION_LABEL_RE = re.compile(
    r"(?:氏名|お名前|担当者|代表者|名義人?)\s*[::]\s*"
    rf"(?P<value>(?P<name>{_NAME})\s*(?:[((、,]|所属\s*[::])\s*(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)"
)
# 「山田太郎さん、株式会社ABC」「山田太郎氏(株式会社ABC 営業部)」
NAME_AFFILIATION_SUFFIX_RE = re.compile(
    rf"(?P<value>(?P<name>{_NAME})(?:さん|氏|様|先生)[、,\s((]+(?P<affiliation>{_ORG}{_DEPT}{_TITLE_OPT})[))]?)"
)
# 「株式会社ABC 営業部 部長 山田太郎さん」「○○大学教授・山田太郎氏」(所属→役職→氏名の順)。
# 役職か「・」区切りのどちらかと、敬称を必須にする。「会社の同僚さん」のような役割語を氏名にしないため。
AFFILIATION_NAME_RE = re.compile(
    rf"(?P<value>(?P<affiliation>{_ORG}{_DEPT})\s*(?:(?:の)?\s*{_TITLE}\s*(?:・|の|\s)?|・)\s*(?P<name>{_NAME})(?:さん|氏|様|先生))"
)
# 個人名だけ(ラベル文脈)。かな名も許可し、フォームの定型語は除外する。
_NAME_TOKEN = r"[一-龥々ぁ-ゖァ-ヶー]{1,8}"
NAME_CONTEXT_RE = re.compile(
    r"(?:氏名|お名前|名前|担当者|代表者|名義人?)\s*[::]\s*"
    rf"(?P<value>{_NAME_TOKEN}(?:\s*{_NAME_TOKEN})?)"
)
NAME_STOPWORDS = {"必須", "任意", "未定", "なし", "不明", "非公開", "匿名", "ニックネーム", "ハンドルネーム", "例", "未入力", "空欄", "入力"}
# 欧文氏名は署名(by / Author / 執筆者)か敬称(Mr. / Dr.)の文脈に限る。単独の「John Smith」は地名・商品名と区別できないため対象外。
LATIN_NAME_RE = re.compile(
    r"(?:(?i:\bby|\bauthor|\bwritten by|\bphoto by|\btext by|\bposted by)|執筆者|著者|文責|撮影|取材|記者|翻訳|監修)\s*[::]?\s*"
    r"(?P<value>(?:(?:Mr|Ms|Mrs|Dr|Prof)\.?\s+)?[A-Z][a-z]+(?:\s[A-Z]\.?)?\s[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)"
    r"|(?P<value2>(?:Mr|Ms|Mrs|Dr|Prof)\.\s+[A-Z][a-z]+(?:\s[A-Z][a-z]+)?)"
)
BANK_CONTEXT_RE = re.compile(
    r"(?:口座番号|口座|振込先|銀行口座)\D{0,20}(?P<value>\d{7})(?!\d)"
)
# URL では数字列がIDであることが多く、番号系の検出は行わない(メール・電話のみ)。
URL_EXCLUDED_TYPES = frozenset({"my_number", "credit_card", "bank_account"})


def _has_context(text: str, position: int, pattern: re.Pattern[str], window: int) -> bool:
    """position の直前 window 文字以内に pattern があるか。"""

    return pattern.search(text, max(0, position - window), position) is not None


# --- 形態素解析による人名検出 -------------------------------------------------
# SudachiPy(Apache-2.0)の辞書は姓・名を「名詞,固有名詞,人名,姓/名」として持つ。
# 姓+名の連続、または敬称・役割ラベル付きの単独人名を候補にし、所属・役職の文脈が
# 近くにあれば「個人名+所属」、敬称・役割ラベルがあれば「個人名」として置換する。
# 文脈のない裸の姓名(「尾田栄一郎はどんな人」)は既定では置換せず、件数だけ数える。
HONORIFIC_AFTER_RE = re.compile(r"(?:さん|氏|様|先生|くん|君|ちゃん|さま)")
# 役割ラベル。1文字の語(文・絵・訳・作・画)は「名作」「原作」を拾わないよう、区切り文字か行頭の直後に限る。
# 出演・司会は俳優・司会者(公人)を指すため含めない。
ROLE_LABEL_BEFORE_RE = re.compile(
    r"(?:(?:執筆者|執筆|著者|文責|記者|編集者|担当者?|講師|監修|取材|撮影|翻訳|写真|(?i:by))|(?:^|[\s、,::・/||((【\[])(?:文|絵|訳|作|画))\s*[::=]?\s*$",
)
TITLE_CONTEXT_RE = re.compile(
    r"(?:代表取締役|取締役|社長|副社長|会長|副会長|理事長|理事|専務|常務|執行役員|部長|次長|課長|係長|主任|所長|院長|校長|園長|館長|局長|"
    r"教授|准教授|助教|講師|研究員|主席|主幹|(?i:ceo|cto|coo|cfo)|マネージャー|ディレクター|プロデューサー|エンジニア|デザイナー|コンサルタント|"
    r"アナリスト|弁護士|税理士|会計士|司法書士|行政書士|社労士|医師|看護師|薬剤師|"
    r"代表|担当|職員|社員|スタッフ|広報|主宰|オーナー|店長|支配人|学長|総長|会員|委員長|委員)"
    # 監督・選手・議員・市長・知事・大臣など公人を示す役職は含めない(公人名は学習データとして保持する)。
)
NAME_CONTEXT_WINDOW = 25
_SENTENCE_BREAK_RE = re.compile(r"[。!?!?\n]")


def _same_sentence_window(text: str, start: int, end: int, window: int) -> tuple[str, str]:
    """氏名の前後 window 文字のうち、同じ文(句点・改行で区切られない範囲)だけを返す。"""

    before = text[max(0, start - window):start]
    after = text[end:end + window]
    breaks = list(_SENTENCE_BREAK_RE.finditer(before))
    if breaks:
        before = before[breaks[-1].end():]
    cut = _SENTENCE_BREAK_RE.search(after)
    if cut:
        after = after[:cut.start()]
    return before, after


class SudachiNameFinder:
    """本文から人名の範囲(姓+名の連続、または単独の姓・名)を返す。"""

    CHUNK_CHARS = 8000  # Sudachi の入力上限(49,149バイト)に収める

    def __init__(self) -> None:
        from sudachipy import Dictionary, SplitMode

        self._tokenizer = Dictionary(dict="core").create()
        self._mode = SplitMode.A

    def _chunks(self, text: str):
        start = 0
        while start < len(text):
            end = min(len(text), start + self.CHUNK_CHARS)
            if end < len(text):
                newline = text.rfind("\n", start + self.CHUNK_CHARS // 2, end)
                if newline > 0:
                    end = newline + 1
            yield start, text[start:end]
            start = end

    def find(self, text: str) -> list[tuple[int, int, str]]:
        """(start, end, kind) を返す。kind は ``pair``(姓+名)か ``single``。"""

        spans: list[tuple[int, int, str]] = []
        for offset, piece in self._chunks(text):
            run: list[tuple[int, int, str]] = []  # (start, end, 姓/名/一般)

            def flush() -> None:
                if not run:
                    return
                kinds = [kind for _, _, kind in run]
                start, end = run[0][0], run[-1][1]
                if "姓" in kinds and "名" in kinds and kinds.index("姓") < len(kinds) - 1:
                    spans.append((start, end, "pair"))
                elif len(run) >= 2 and end - start >= 3:
                    spans.append((start, end, "pair"))
                elif end - start >= 2:
                    spans.append((start, end, "single"))
                run.clear()

            pending_connector = False
            for morpheme in self._tokenizer.tokenize(piece, self._mode):
                pos = morpheme.part_of_speech()
                surface = morpheme.surface()
                if pos[2] == "人名":
                    run.append((offset + morpheme.begin(), offset + morpheme.end(), pos[3]))
                    pending_connector = False
                elif run and not pending_connector and (pos[0] == "空白" or surface in ("・", "・", "=", "=")):
                    # 「山田 太郎」「ジョン・スミス」の空白・中黒は1つだけ連結として扱う
                    pending_connector = True
                else:
                    flush()
                    pending_connector = False
            flush()
        return spans


def _digits(value: str) -> str:
    return "".join(char for char in value if char.isdigit())


def _valid_phone(value: str) -> bool:
    digits = _digits(value)
    if value.startswith("+81"):
        digits = "0" + digits[2:]
    if len(digits) not in {10, 11} or not digits.startswith("0"):
        return False
    if digits.startswith(("070", "080", "090")):
        return len(digits) == 11
    return digits[1] in "123456789" and len(digits) in {10, 11}


def _overlap(first: PIIMatch, second: PIIMatch) -> bool:
    return first.start < second.end and second.start < first.end


def _select_non_overlapping(matches: Iterable[PIIMatch]) -> list[PIIMatch]:
    """重なった候補は、長く信頼度の高い候補を優先して1回だけ置換する。"""

    confidence_rank = {"high": 2, "medium": 1, "low": 0}
    ordered = sorted(
        matches,
        key=lambda item: (
            item.start,
            -(item.end - item.start),
            -confidence_rank.get(item.confidence, 0),
        ),
    )
    selected: list[PIIMatch] = []
    for candidate in ordered:
        if any(_overlap(candidate, existing) for existing in selected):
            continue
        selected.append(candidate)
    return sorted(selected, key=lambda item: (item.start, item.end, item.pii_type))


class PIIDetector:
    """URLと本文から指定7種類だけを検出し、プレースホルダーへ置換する。"""

    def __init__(
        self,
        include_url: bool = True,
        use_sudachi: bool = True,
        mask_honorific_names: bool = False,
        mask_bare_names: bool = False,
        name_context_window: int = NAME_CONTEXT_WINDOW,
        affiliation_titles: bool = True,
    ) -> None:
        self.include_url = include_url
        self.use_sudachi = use_sudachi
        self.name_context_window = name_context_window
        # 既定では組織名(法人格・組織語尾)と役職語(代表取締役、教授等)の両方を所属文脈とする。
        # 組織名だけに狭める場合は affiliation_titles=False(CLI: --no-affiliation-titles)。
        self.affiliation_titles = affiliation_titles
        self.mask_honorific_names = mask_honorific_names
        self.mask_bare_names = mask_bare_names
        self._names: SudachiNameFinder | None = None
        # 置換しなかった姓名の件数(方針判断用)。敬称のみ/文脈なし。
        self.honorific_name_candidates = 0
        self.honorific_name_records = 0
        self.bare_name_candidates = 0
        self.bare_name_records = 0

    def _name_finder(self) -> SudachiNameFinder:
        if self._names is None:
            self._names = SudachiNameFinder()
        return self._names

    def _detect_names(self, normalized: str, field: str) -> list[PIIMatch]:
        matches: list[PIIMatch] = []
        bare = 0
        honorific_only = 0
        for start, end, kind in self._name_finder().find(normalized):
            value = normalized[start:end]
            before, after = _same_sentence_window(normalized, start, end, self.name_context_window)
            honorific = HONORIFIC_AFTER_RE.match(normalized, end) is not None
            role = ROLE_LABEL_BEFORE_RE.search(normalized[max(0, start - 16):start]) is not None
            affiliated = bool(_ORG_RE.search(before) or _ORG_RE.search(after))
            if not affiliated and self.affiliation_titles:
                affiliated = bool(TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after))
            if affiliated and (kind == "pair" or honorific or role):
                matches.append(PIIMatch("person_affiliation", field, start, end, value, "sudachi_name_affiliation", "medium"))
            elif role:
                matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_role", "medium"))
            elif honorific:
                # 「○○さん」だけでは私人か公人(俳優、作家、選手)か区別できないため、既定では置換しない。
                if self.mask_honorific_names:
                    matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_honorific", "low"))
                else:
                    honorific_only += 1
            elif kind == "pair":
                if self.mask_bare_names:
                    matches.append(PIIMatch("person_name", field, start, end, value, "sudachi_name_bare", "low"))
                else:
                    bare += 1
        if honorific_only:
            self.honorific_name_candidates += honorific_only
            self.honorific_name_records += 1
        if bare:
            self.bare_name_candidates += bare
            self.bare_name_records += 1
        return matches

    @staticmethod
    def _looks_like_phone(value: str) -> bool:
        """住所候補の末尾が電話番号(区切り付き10桁以上)なら住所とみなさない。"""

        tail = re.search(r"(\d+(?:\s?[--‐ー]\s?\d+)+)\s*$", value)
        if not tail:
            return False
        digits = _digits(tail.group(1))
        return len(digits) >= 9 and "丁目" not in value[-20:] and "番" not in value[-20:]

    def detect(self, text: Any, field: str = "content") -> list[PIIMatch]:
        normalized = normalize_text(text)
        if not normalized:
            return []
        matches: list[PIIMatch] = []

        def add(
            pattern: re.Pattern[str],
            pii_type: str,
            method: str,
            confidence: str = "high",
            group: str | None = None,
        ) -> None:
            for found in pattern.finditer(normalized):
                value = found.group(group) if group else found.group(0)
                start = found.start(group) if group else found.start()
                end = found.end(group) if group else found.end()
                matches.append(PIIMatch(pii_type, field, start, end, value, method, confidence))

        add(EMAIL_RE, "email", "regex_email")
        for found in PHONE_SEPARATED_RE.finditer(normalized):
            value = found.group("value")
            if _valid_phone(value):
                matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "regex_phone"))
        for found in PHONE_MOBILE_RE.finditer(normalized):
            if _valid_phone(found.group(0)):
                matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone"))
        for found in PHONE_PLAIN_RE.finditer(normalized):
            if _valid_phone(found.group(0)):
                matches.append(PIIMatch("phone", field, found.start(), found.end(), found.group(0), "regex_phone"))
        for found in PHONE_CONTEXT_RE.finditer(normalized):
            value = found.group("value")
            if _valid_phone(value):
                matches.append(PIIMatch("phone", field, found.start("value"), found.end("value"), value, "context_phone", "medium"))

        if field != "url":
            for found in MY_NUMBER_RE.finditer(normalized):
                value = found.group(0)
                if not is_valid_mynumber(value):
                    continue
                if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20):
                    continue
                # 区切り書式だけでは数表・型番を誤検出するため、マイナンバーはラベル文脈を必須にする。
                if _has_context(normalized, found.start(), MY_NUMBER_CONTEXT_RE, 40):
                    matches.append(PIIMatch("my_number", field, found.start(), found.end(), value, "checksum_mynumber"))
            for found in CARD_RE.finditer(normalized):
                value = found.group(0)
                if not is_valid_luhn(value) or len(_digits(value)) == 12:
                    continue
                if _has_context(normalized, found.start(), NUMBER_NEGATIVE_CONTEXT_RE, 20):
                    continue
                labeled = _has_context(normalized, found.start(), CARD_CONTEXT_RE, 40)
                grouped = not value.isdigit()
                if labeled or grouped:
                    matches.append(PIIMatch("credit_card", field, found.start(), found.end(), value, "checksum_luhn", "high" if labeled else "medium"))

        patterns = [
            (ADDRESS_RE, "address", "regex_address"),
            (ADDRESS_CITY_RE, "address", "regex_address_city"),
            (ADDRESS_CONTEXT_RE, "address", "context_address"),
            (NAME_AFFILIATION_LABEL_RE, "person_affiliation", "context_name_affiliation"),
            (NAME_AFFILIATION_SUFFIX_RE, "person_affiliation", "context_name_affiliation"),
            (AFFILIATION_NAME_RE, "person_affiliation", "context_affiliation_name"),
        ]
        if field != "url":
            patterns.append((BANK_CONTEXT_RE, "bank_account", "context_bank_account"))
        for pattern, pii_type, method in patterns:
            add(pattern, pii_type, method, "medium", "value")
        matches = [m for m in matches if not (m.pii_type == "address" and self._looks_like_phone(m.value))]
        if self.use_sudachi and field != "url":
            matches.extend(self._detect_names(normalized, field))
        for found in LATIN_NAME_RE.finditer(normalized):
            group = "value" if found.group("value") else "value2"
            matches.append(PIIMatch("person_name", field, found.start(group), found.end(group), found.group(group), "context_latin_name", "medium"))
        for found in NAME_CONTEXT_RE.finditer(normalized):
            value = found.group("value")
            if value in NAME_STOPWORDS or value.split()[0] in NAME_STOPWORDS:
                continue
            matches.append(PIIMatch("person_name", field, found.start("value"), found.end("value"), value, "context_name", "medium"))

        # 同一type・同一位置の重複を除き、出現順に返す。重複範囲は検出結果として
        # 残すが、置換時には _select_non_overlapping で一つにまとめる。
        unique: dict[tuple[str, str, int, int], PIIMatch] = {}
        for match in matches:
            unique[(match.pii_type, match.field, match.start, match.end)] = match
        return sorted(unique.values(), key=lambda item: (item.start, item.end, item.pii_type))

    def detect_record(self, url: Any, content: Any) -> list[PIIMatch]:
        matches: list[PIIMatch] = []
        if self.include_url:
            matches.extend(self.detect(url, "url"))
        matches.extend(self.detect(content, "content"))
        return matches

    def replace_text(self, text: Any, field: str = "content") -> tuple[str, list[PIIMatch]]:
        """PIIをプレースホルダーに置換し、実際に置換した候補を返す。

        NFKC正規化後の文字列を返すため、全角のメールアドレス等も一貫した
        表記になる。検出位置は返却文字列(置換前のNFKC文字列)に対応する。
        """

        normalized = normalize_text(text)
        if not normalized:
            return normalized, []
        selected = _select_non_overlapping(self.detect(normalized, field))
        replaced = normalized
        for match in reversed(selected):
            replaced = replaced[: match.start] + match.placeholder + replaced[match.end :]
        return replaced, selected

    def replace_record(self, url: Any, content: Any) -> tuple[str, str, list[PIIMatch]]:
        replaced_url, url_matches = (self.replace_text(url, "url") if self.include_url else (normalize_text(url), []))
        replaced_content, content_matches = self.replace_text(content, "content")
        return replaced_url, replaced_content, url_matches + content_matches


def matches_to_dict(matches: Iterable[PIIMatch]) -> list[dict[str, Any]]:
    return [match.to_dict() for match in matches]