#!/usr/bin/env python3
"""Public CI check for personal data patterns that don't need a private denylist.

Flags phone-style WhatsApp JIDs, GUIDs, email addresses, Tailscale names and private IPs unless
they are obviously fictional (1555 numbers, repeated-digit GUIDs, example.com addresses).
Prints file:line and the pattern name, never the value.
"""
import re
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SKIP = {'scripts/check-generic-pii', 'uv.lock', 'bot/uv.lock'}
PATTERNS = {
    'whatsapp jid': re.compile(r'\b(\d{8,})@(s\.whatsapp\.net|lid|g\.us)\b'),
    'guid': re.compile(r'\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b'),
    'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'),
    'tailscale name': re.compile(r'\b[a-z0-9-]+\.ts\.net\b'),
    'private ip': re.compile(r'\b(10\.\d+|192\.168|172\.(1[6-9]|2\d|3[01])|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7]))\.\d+\.\d+\b'),
    'home path': re.compile(r'/(home|Users)/[a-z][a-z0-9_-]+/'),
}


def fictional(kind, match):
    value = match.group(0)
    if kind == 'whatsapp jid':
        digits = match.group(1)
        return digits.startswith(('1555', '100000', '120363000000')) or set(digits[2:]) <= {'0', '1'}
    if kind == 'guid':
        groups = value.lower().split('-')
        return len(set(''.join(groups))) <= 2 or all(len(set(g)) == 1 for g in groups)
    if kind == 'email':
        domain = value.split('@', 1)[1].lower()
        return (domain in ('example.com', 'example.org', 'users.noreply.github.com', 's.whatsapp.net',
                           'lid', 'g.us') or domain.endswith(('.example.com', 'whatsapp.net', 'thread.v2',
                                                              'spaces', 'thread.skype')))
    return False


def main():
    out = subprocess.run(['git', 'ls-files', '-co', '--exclude-standard', '-z'], cwd=ROOT,
                         capture_output=True, check=True).stdout.decode()
    hits = []
    for rel in filter(None, out.split('\0')):
        path = ROOT / rel
        if rel in SKIP or not path.is_file() or path.suffix in ('.png', '.zip'):
            continue
        for lineno, line in enumerate(path.read_text(errors='replace').splitlines(), 1):
            for kind, pattern in PATTERNS.items():
                if any(not fictional(kind, m) for m in pattern.finditer(line)):
                    hits.append(f'{rel}:{lineno}: {kind}')
    print('\n'.join(hits) or 'clean')
    return 1 if hits else 0


if __name__ == '__main__':
    sys.exit(main())
