#!/usr/bin/env python3
"""Install the Elderly monthly report and Excel export; no migrations, environment or service changes."""
from pathlib import Path
import datetime
import hashlib
import json
import os
import shutil
import subprocess

ROOT = Path('/var/www/html/artcare')
DEPLOY = ROOT / 'storage/app/elderly-support-monthly-report-20261016'
STAGE = DEPLOY / 'stage'
ORDER = ['resources/data/elderly-support-monthly-report.json', 'app/Support/ElderlySupportMonthlyReport.php', 'app/Exports/ElderlySupport/MonthlyReportExport.php', 'app/Http/Controllers/ElderlySupport/MonthlyReportController.php', 'resources/views/Elderly_support/partials/navigation.blade.php', 'resources/views/Elderly_support/monthly_report.blade.php', 'public/css/elderly-support-monthly-report.css', 'public/js/elderly-support-monthly-report.js', 'resources/views/Elderly_support/layouts/app.blade.php', 'resources/views/Elderly_support/register.blade.php', 'routes/elderly_support_web.php', 'public/elderly-support/service-worker.js']
SERVICES = ['apache2', 'cloudflared', 'cloudflared-elderly-support']
digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()


def routes():
    result = subprocess.run(['php', 'artisan', 'route:list', '--json'], cwd=ROOT, text=True, capture_output=True, check=True)
    return json.loads(result.stdout)


def services():
    return {name: subprocess.run(['systemctl', 'show', name, '-p', 'MainPID', '--value'], text=True, capture_output=True, check=True).stdout.strip() for name in SERVICES}


def main():
    manifest = json.loads((STAGE / 'manifest.json').read_text())
    if sorted(row['path'] for row in manifest) != sorted(ORDER):
        raise RuntimeError('Unexpected deployment scope')
    by_path = {row['path']: row for row in manifest}
    for path in ORDER:
        item = by_path[path]
        if digest(STAGE / path) != item['sha256']:
            raise RuntimeError('Stage checksum mismatch: ' + path)
        if (ROOT / path).exists():
            if digest(ROOT / path) not in {item.get('before_sha256'), item['sha256']}:
                raise RuntimeError('Live file changed: ' + path)
        elif item.get('before_sha256') is not None:
            raise RuntimeError('Live file missing: ' + path)
        if path.endswith('.php'):
            subprocess.run(['php', '-l', str(STAGE / path)], check=True, capture_output=True)
    before_routes, before_services = routes(), services()
    env_digest = digest(ROOT / '.env')
    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    backup = ROOT / '.local-backups' / ('elderly-support-monthly-report-' + stamp)
    backup.mkdir(mode=0o700)
    for path in ORDER:
        saved = backup / path
        saved.parent.mkdir(parents=True, exist_ok=True)
        if (ROOT / path).exists(): shutil.copy2(ROOT / path, saved)
    (backup / 'manifest.json').write_text(json.dumps(manifest, indent=2))
    (backup / 'routes-before.json').write_text(json.dumps(before_routes, indent=2))
    for path in ORDER:
        target = ROOT / path
        target.parent.mkdir(parents=True, exist_ok=True)
        temporary = target.with_name('.' + target.name + '.elderly-monthly-report-next')
        if temporary.exists():
            raise RuntimeError('Unexpected temporary file: ' + str(temporary))
        shutil.copyfile(STAGE / path, temporary)
        os.chmod(temporary, 0o644)
        os.replace(temporary, target)
    after_routes, after_services = routes(), services()
    old_other = [r for r in before_routes if r.get('domain') != 'elderly.mam-app.org']
    new_other = [r for r in after_routes if r.get('domain') != 'elderly.mam-app.org']
    if old_other != new_other:
        raise RuntimeError('Unrelated route definitions changed')
    old_elderly = [r for r in before_routes if r.get('domain') == 'elderly.mam-app.org']
    new_elderly = [r for r in after_routes if r.get('domain') == 'elderly.mam-app.org']
    if any(r not in new_elderly for r in old_elderly) or len(new_elderly) != 28:
        raise RuntimeError('Unexpected Elderly route definitions')
    if before_services != after_services:
        raise RuntimeError('A service process changed during deployment; inspect continuity')
    if env_digest != digest(ROOT / '.env'):
        raise RuntimeError('Environment changed')
    for path in ORDER:
        if digest(ROOT / path) != by_path[path]['sha256']:
            raise RuntimeError('Installed checksum mismatch: ' + path)
    result = {'applied_at': stamp, 'backup': str(backup), 'runtime_files_updated': len(manifest),
              'migrations_run': False, 'environment_unchanged': True, 'services_restarted': False,
              'service_pids': after_services, 'existing_routes_preserved': len([r for r in after_routes if r.get('domain') != 'elderly.mam-app.org']),
              'elderly_routes': len([r for r in after_routes if r.get('domain') == 'elderly.mam-app.org']),
              'worker_cache': 'elderly-support-shell-v10-monthly-report-20261016'}
    (DEPLOY / 'deployment-result.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
