#!/usr/bin/env python3
"""Check template/Python translation keys against BASE_TRANSLATIONS."""
from pathlib import Path
import ast, re, sys
root=Path(__file__).resolve().parents[1]
source=(root/'app'/'i18n.py').read_text(encoding='utf-8')
tree=ast.parse(source)
keys=set()
for node in ast.walk(tree):
    if isinstance(node, ast.Dict):
        for key in node.keys:
            if isinstance(key, ast.Constant) and isinstance(key.value,str): keys.add(key.value)
used=set()
patterns=[re.compile(r"\bt\(\s*['\"]([^'\"]+)"),re.compile(r"_translate_request\([^,]+,\s*['\"]([^'\"]+)")]
for path in list((root/'app').rglob('*.py'))+list((root/'app'/'templates').rglob('*.html')):
    text=path.read_text(encoding='utf-8',errors='replace')
    for pattern in patterns: used.update(pattern.findall(text))
dynamic_prefixes=('field.','jobdefs.interpreter.','jobdefs.platform.','jobdefs.source.','jobs.action.','jobs.event.','jobs.type.','presence.','software.platform.','software.status.','backup.reason_')
missing=sorted(k for k in used if k not in keys and '~' not in k and not k.startswith(dynamic_prefixes))
jobdef_used=sorted(k for k in used if k.startswith('jobdefs.') and not k.endswith('.'))
jobdef_missing=sorted(k for k in jobdef_used if k not in keys and not k.startswith(('jobdefs.interpreter.','jobdefs.platform.','jobdefs.source.')))
if jobdef_missing:
    print('Missing jobdefs keys:')
    for key in jobdef_missing: print(' -',key)
    sys.exit(1)
print(f'Defined translation keys: {len(keys)}')
print(f'Statically referenced keys: {len(used)}')
if missing:
    print('Legacy/static keys without BASE_TRANSLATIONS entry (warning):')
    for key in missing: print(' -',key)
print('Job definition translation check passed.')
