#!/usr/bin/env python3
from pathlib import Path
import argparse, sys

parser=argparse.ArgumentParser(description='Apply Lemenzo Clock integration to a LemenzoOS source tree.')
parser.add_argument('--root', default='.', help='Android source tree root')
parser.add_argument('--finalize-replacement', action='store_true', help='Remove DeskClock from handheld_product.mk after LemenzoClock build/tests are green')
a=parser.parse_args()
root=Path(a.root).resolve()

secure=root/'vendor/secureline/secureline.mk'
policy=root/'frameworks/base/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java'
handheld=root/'build/make/target/product/handheld_product.mk'

for p in (secure,policy):
    if not p.exists():
        sys.exit(f'ERROR: required file not found: {p}')

# PRODUCT_PACKAGES
s=secure.read_text()
if 'LemenzoClock' not in s:
    anchors=['LemenzoCalculator \\\n','LemenzoFiles \\\n','LemenzoCamera \\\n']
    for anchor in anchors:
        if anchor in s:
            s=s.replace(anchor, anchor+'LemenzoClock \\\n',1)
            break
    else:
        sys.exit('ERROR: could not find a safe Lemenzo app anchor in vendor/secureline/secureline.mk')
    secure.write_text(s)
    print('OK: added LemenzoClock to vendor/secureline/secureline.mk')
else:
    print('OK: LemenzoClock already present in vendor/secureline/secureline.mk')

# Notification pre-grant: keep READ_CALENDAR opt-in.
s=policy.read_text()
if '"com.lemenzo.clock"' not in s:
    anchor='"com.lemenzo.camera",'
    if anchor not in s:
        sys.exit('ERROR: com.lemenzo.camera notification-grant anchor not found in DefaultPermissionGrantPolicy.java')
    s=s.replace(anchor, anchor+'\n            "com.lemenzo.clock",',1)
    policy.write_text(s)
    print('OK: added com.lemenzo.clock to system notification grants')
else:
    print('OK: com.lemenzo.clock notification grant already present')

if a.finalize_replacement:
    if not handheld.exists():
        sys.exit(f'ERROR: handheld product file not found: {handheld}')
    s=handheld.read_text()
    old='    DeskClock \\\n'
    if old in s:
        handheld.write_text(s.replace(old,'',1))
        print('OK: removed DeskClock from handheld_product.mk')
    elif 'DeskClock' in s:
        sys.exit('ERROR: DeskClock exists in unexpected format; remove it manually after review')
    else:
        print('OK: DeskClock already absent from handheld_product.mk')
else:
    print('INFO: DeskClock kept. Use --finalize-replacement only after m LemenzoClock LemenzoClockTests is green.')

print('OK: Lemenzo Clock system integration complete')
