#!/usr/bin/env python3
"""Install automatic Elderly IDs and run only its reservation-table migration. No service restart."""
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-auto-ids-20261017'
STAGE = DEPLOY / 'stage'
ORDER = ['database/migrations/2026_10_17_000300_create_elderly_support_program_ids_table.php', 'app/Support/ElderlySupportProgramIds.php', 'config/elderly_support.php', 'resources/data/elderly-support-register.json', 'resources/data/elderly-support-followup.json', 'app/Support/ElderlySupportSchema.php', 'app/Support/ElderlySupportSync.php', 'app/Support/ElderlySupportFollowupSync.php', 'app/Http/Controllers/ElderlySupport/RegisterController.php', 'resources/views/Elderly_support/partials/field.blade.php', 'public/js/elderly-support-core.js', 'public/js/elderly-support-program-ids.js', 'public/js/elderly-support-app.js', 'public/elderly-support/elderly-support-data-dictionary.xlsx', 'resources/views/Elderly_support/register.blade.php', 'resources/views/Elderly_support/monthly_report.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)
    database_check = subprocess.run(['php','-r', 'require "vendor/autoload.php"; $app=require "bootstrap/app.php"; $app->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap(); if(config("elderly_support.connection")!=="MAM_NAP")exit(2); echo Illuminate\\Support\\Facades\\DB::connection("MAM_NAP")->selectOne("SELECT DATABASE() AS db_name")->db_name;'], cwd=ROOT, text=True, capture_output=True, check=True).stdout.strip()
    if database_check != 'MAM_NAP': raise RuntimeError('Unexpected physical database')
    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-auto-ids-' + 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-auto-ids-next')
        if temporary.exists():
            raise RuntimeError('Unexpected temporary file: ' + str(temporary))
        shutil.copyfile(STAGE / path, temporary)
        os.chmod(temporary, 0o644)
        os.replace(temporary, target)
        if path == ORDER[0]:
            migration = subprocess.run(['php','artisan','migrate','--database=MAM_NAP','--path='+path,'--force','--no-interaction'],cwd=ROOT,text=True,capture_output=True,check=True)
            (DEPLOY / 'migration-output.txt').write_text(migration.stdout + migration.stderr)

    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) != 29:
        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': True, 'migration': ORDER[0], 'database': 'MAM_NAP', '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-v12-automatic-ids-20261017'}
    (DEPLOY / 'deployment-result.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
