"""Scan active demo data, Office metadata, PDFs, mail and the downloadable forms archive.

Flags unknown email addresses and potentially identifying Word metadata/resources.
Names, addresses and pictures also require human review; this is a regression gate,
not a claim that arbitrary personal information can be detected automatically.
"""
from pathlib import Path
import io, json, re, sys, zipfile, xml.etree.ElementTree as ET
from email import policy
from email.parser import BytesParser
from pypdf import PdfReader

ROOT = Path(__file__).resolve().parent.parent
ALLOWED = {'office@fakecompany.eu', 'office@baerenstahl.dev'}
EMAIL = re.compile(r'(?<![@\w])[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,}', re.I)
findings = []; inspected = 0

def text_check(text, name):
    for email in set(EMAIL.findall(text)):
        # Fictional SQL @database-link syntax in the legacy migration sample.
        if email.lower() not in ALLOWED and not email.lower().endswith('@demo.invalid'):
            findings.append({'file': name, 'kind': 'email outside approved demo addresses'})

def inspect(data, suffix, name):
    global inspected
    inspected += 1
    try:
        if suffix == '.docx':
            with zipfile.ZipFile(io.BytesIO(data)) as archive:
                for member in archive.namelist():
                    if member.startswith(('word/embeddings/', 'customXml/')): findings.append({'file':name, 'kind':'embedded/custom data needs review'})
                    if member.endswith(('.xml','.rels')):
                        raw = archive.read(member); text_check(raw.decode('utf8',errors='replace'),name)
                        tree = ET.fromstring(raw)
                        if member == 'docProps/core.xml':
                            for node in tree.iter():
                                if node.tag.split('}')[-1] in ['creator','lastModifiedBy'] and node.text not in [None,'','Fake Company','Demo Operator']:
                                    findings.append({'file':name,'kind':'Word author metadata needs review'})
        elif suffix == '.pdf':
            reader = PdfReader(io.BytesIO(data))
            text_check('\n'.join(page.extract_text() or '' for page in reader.pages) + str(reader.metadata),name)
        elif suffix == '.eml':
            message = BytesParser(policy=policy.default).parsebytes(data)
            text_check(str(message.items()),name)
            for part in message.walk():
                if part.get_content_maintype() == 'text': text_check(part.get_content(),name)
                elif part.get_filename(): inspect(part.get_payload(decode=True),Path(part.get_filename()).suffix.lower(),name+' / attachment')
        elif suffix == '.zip':
            with zipfile.ZipFile(io.BytesIO(data)) as archive:
                for entry in archive.infolist():
                    if not entry.is_dir(): inspect(archive.read(entry),Path(entry.filename).suffix.lower(),name+' / '+entry.filename)
        elif suffix in ['.json','.xml','.rels','.fo','.js','.ps1','.php','.txt','.md','.svg','.html','.css','.cs','.py','.mjs']:
            text_check(data.decode('utf8',errors='replace'),name)
    except Exception as error: findings.append({'file':name,'kind':'unreadable: '+type(error).__name__})

for folder in ['data','uiframework/sampledocs','forms/screenshots','forms/generated']:
    for path in (ROOT/folder).rglob('*'):
        if path.is_file(): inspect(path.read_bytes(),path.suffix.lower(),path.relative_to(ROOT).as_posix())
inspect((ROOT/'forms/forms.zip').read_bytes(),'.zip','forms/forms.zip')
for path in (ROOT/'uiframework/cloccojs').glob('*.js'):
    inspect(path.read_bytes(),'.js',path.relative_to(ROOT).as_posix())
for path in list((ROOT/'uiframework').glob('*.php')) + [ROOT/'uiframework/README.md']:
    inspect(path.read_bytes(),path.suffix,path.relative_to(ROOT).as_posix())
if '--include-history' in sys.argv:
    for path in (ROOT/'uiframework/versions').rglob('*'):
        if path.is_file() and path.suffix in ['.js','.html','.md','.php']:
            inspect(path.read_bytes(),path.suffix,path.relative_to(ROOT).as_posix())
print(json.dumps({'inspected':inspected,'findings':findings,'allowedEmails':sorted(ALLOWED)},indent=2))
sys.exit(bool(findings))
