#!/usr/bin/env python3
"""Combine caregiver and requested-support cards and renumber sections; 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-caregiver-card-20261020'
STAGE = DEPLOY / 'stage'
ORDER = ['resources/data/elderly-support-register.json', 'public/elderly-support/elderly-support-data-dictionary.xlsx', 'resources/views/Elderly_support/register.blade.php', 'resources/views/Elderly_support/monthly_report.blade.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-caregiver-card-' + 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-caregiver-card-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()
    if before_routes != after_routes:
        raise RuntimeError('Route definitions changed')
    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-v16-caregiver-card-20261020'}
    (DEPLOY / 'deployment-result.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
