#!/usr/bin/env python3
from pathlib import Path
import re, sys, xml.etree.ElementTree as ET
root=Path(__file__).resolve().parents[1]
errors=[]
def need(ok,msg):
    if not ok: errors.append(msg)

manifest=(root/'AndroidManifest.xml').read_text()
need('package="com.lemenzo.clock"' in manifest,'package must be com.lemenzo.clock')
need('android.permission.INTERNET' not in manifest,'Clock must not request INTERNET')
need('android.permission.USE_EXACT_ALARM' in manifest,'exact alarm permission missing')
need('android.permission.USE_FULL_SCREEN_INTENT' in manifest,'full-screen alarm permission missing')
need('overrides: ["DeskClock"]' in (root/'Android.bp').read_text(),'DeskClock override missing')

base=ET.parse(root/'res/values/strings.xml').getroot()
base_names={e.attrib['name'] for e in base.findall('string')}
for lang in ('da','de','es','sv','no'):
    names={e.attrib['name'] for e in ET.parse(root/f'res/values-{lang}/strings.xml').getroot().findall('string')}
    need(names==base_names,f'{lang} translation coverage mismatch: missing={sorted(base_names-names)} extra={sorted(names-base_names)}')

for p in root.rglob('*.xml'):
    try: ET.parse(p)
    except Exception as e: errors.append(f'Invalid XML {p.relative_to(root)}: {e}')

# Validate local resource references to catch AAPT link failures early.
resources=set()
for base_dir in (root/'res').iterdir():
    if not base_dir.is_dir():
        continue
    rtype=base_dir.name.split('-')[0]
    if rtype=='values':
        for xml in base_dir.glob('*.xml'):
            tree=ET.parse(xml).getroot()
            for el in tree:
                name=el.attrib.get('name')
                if name:
                    resources.add((el.tag,name))
    else:
        for f in base_dir.iterdir():
            if f.is_file():
                resources.add((rtype,f.stem))
resource_ref=re.compile(r'@(?:(android):)?([A-Za-z0-9_]+)/([A-Za-z0-9_.]+)')
for source in list(root.rglob('*.xml'))+list(root.rglob('*.java')):
    for android_ref,rtype,name in resource_ref.findall(source.read_text(errors='ignore')):
        if android_ref or rtype=='id':
            continue
        need((rtype,name) in resources, f'Missing resource @{rtype}/{name} referenced by {source.relative_to(root)}')

if errors:
    print('\n'.join('ERROR: '+e for e in errors)); sys.exit(1)

# LemenzoOS design/reliability invariants
colors=(root/'res/values/colors.xml').read_text()
assert '#08090C' in colors, 'Lemenzo UI background token must match Lemenzo Phone #08090C'
assert '#3F8CFF' in colors, 'Lemenzo primary blue token missing'
assert '#B7C8E6' in colors, 'Blue-tinted secondary text token missing'
launcher=(root/'res/drawable/ic_launcher_background.xml').read_text()
assert '#000000' in launcher, 'Launcher background must remain #000000'
settings=(root/'src/com/lemenzo/clock/settings/ClockSettings.java').read_text()
assert 'createDeviceProtectedStorageContext' in settings, 'ClockSettings must be Direct-Boot safe'
stopwatch=(root/'src/com/lemenzo/clock/stopwatch/StopwatchRepository.java').read_text()
assert 'started_wall' in stopwatch and 'createDeviceProtectedStorageContext' in stopwatch, 'Stopwatch must be reboot safe'
timer=(root/'src/com/lemenzo/clock/timer/TimerScheduler.java').read_text()
for method in ['pause(', 'resume(', 'reset(']: assert method in timer, 'Timer missing '+method
manifest=(root/'AndroidManifest.xml').read_text()
assert 'LemenzoClockWidgetProvider' in manifest, 'Clock widget provider missing'


# v3.1 premium responsive design invariants
ui=(root/'src/com/lemenzo/clock/util/Ui.java').read_text()
clock=(root/'src/com/lemenzo/clock/ClockActivity.java').read_text()
editor=(root/'src/com/lemenzo/clock/alarm/AlarmEditorActivity.java').read_text()
assert 'WindowInsets.Type.displayCutout()' in ui, 'Display cutout/camera-hole safe insets missing'
assert 'Math.max(bars.top,cutout.top)' in ui, 'Top safe inset must account for status bar and cutout'
assert 'Math.max(bars.left,cutout.left)' in ui and 'Math.max(bars.right,cutout.right)' in ui, 'Landscape cutout side insets missing'
assert 'R.string.nav_world' in clock and 'R.string.nav_stopwatch' in clock, 'Responsive short navigation labels missing'
assert 'Ui.destructive' in clock, 'Alarm destructive action hierarchy missing'
assert 'Ui.styleDayChip' in editor, 'Modern repeat-day chips missing'
assert '<string name="app_name">Clock</string>' in (root/'res/values/strings.xml').read_text(), 'Launcher label must be Clock'
assert 'premiumCard' in clock, 'Premium card hierarchy missing'

print('OK: Lemenzo Clock static validation passed')

# v1.9 integration / branding invariants
notif=root/'res/drawable/ic_notification_clock.xml'
assert notif.exists(), 'Lemenzo notification icon missing'
for p in (root/'src').rglob('*.java'):
    text=p.read_text()
    assert 'android.R.drawable.ic_lock_idle_alarm' not in text, f'Generic Android alarm icon still used in {p.relative_to(root)}'
integration=(root/'integration/apply_lemenzo_clock_integration.py').read_text()
assert '"com.lemenzo.clock"' in integration, 'notification pre-grant integration missing'
assert '--finalize-replacement' in integration, 'safe DeskClock finalization gate missing'
print('OK: v1.9 production integration invariants passed')
