"""Set only the audited PHP production/debug flags, preserving secrets and rollback evidence."""
import importlib.util
import inspect
import json
from pathlib import Path
import subprocess


def production_flags(content):
    import re

    expected = {'APP_ENV': {'local', 'production'}, 'APP_DEBUG': {'true', 'false'}}
    replacements = {'APP_ENV': 'production', 'APP_DEBUG': 'false'}
    for name, allowed in expected.items():
        values = re.findall(r'^' + name + r'=([^\r\n]*)', content, re.MULTILINE)
        if len(values) != 1 or values[0].strip().strip('\"\'') not in allowed:
            raise ValueError('Unexpected or duplicate ' + name + '; reconcile before updating')
    return re.sub(r'^(APP_ENV|APP_DEBUG)=[^\r\n]*', lambda match: match[1] + '=' + replacements[match[1]],
                  content, flags=re.MULTILINE)


def main():
    root = Path(__file__).resolve().parents[1]
    if subprocess.check_output(['git', 'status', '--porcelain'], cwd=root, text=True).strip():
        raise ValueError('Commit the reviewed config operation first')
    revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip()
    spec = importlib.util.spec_from_file_location('deployment_client', root / 'scripts/deploy.py')
    client = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(client)
    config = client.configuration(root / '.deploy/config.json')
    code = r'''
import fcntl, hashlib, json, os, shutil, subprocess, sys
from pathlib import Path
os.umask(0o077)
root=Path('/www/wwwroot/app.connectlyvideochat.com')
target=root/'.env'
if target.is_symlink() or (root/'bootstrap/cache/config.php').exists():
 raise ValueError('Reconcile symlink/cached configuration before mutation')
lock=open('/www/backup/bondvia-deploy/deploy.lock','a')
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
old=target.read_text()
new=production_flags(old)
if old==new:
 print(json.dumps({'changed':False,'environment':'production','debug':False}))
 raise SystemExit(0)
work=Path('/www/backup/bondvia-deploy/audit-config')/sys.argv[1]
if work.exists():raise ValueError('Configuration operation already attempted; inspect before retry')
work.mkdir(parents=True,mode=0o700)
backup=work/'php.env.before'
shutil.copy2(target,backup);backup.chmod(0o600)
assert hashlib.sha256(backup.read_bytes()).digest()==hashlib.sha256(target.read_bytes()).digest()
stat=target.stat()
def replace(content):
 temp=root/'.env.audit-new'
 temp.write_text(content);os.chmod(temp,stat.st_mode&0o777);os.chown(temp,stat.st_uid,stat.st_gid)
 os.replace(temp,target)
replace(new)
try:
 script="chdir('/www/wwwroot/app.connectlyvideochat.com');require 'vendor/autoload.php';$app=require 'bootstrap/app.php';$app->make(\\Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();echo json_encode(['debug'=>config('app.debug'),'environment'=>config('app.env')]);"
 result=subprocess.run(['/www/server/php/83/bin/php','-r',script],capture_output=True,text=True,timeout=30,check=True)
 flags=json.loads(result.stdout)
 if flags!={'debug':False,'environment':'production'}:raise ValueError('Runtime flags differ')
except BaseException:
 replace(old)
 raise RuntimeError('Configuration check failed; previous environment restored')
print(json.dumps({'changed':True,'environment':'production','debug':False,'backup_sha256':hashlib.sha256(backup.read_bytes()).hexdigest(),'secrets_preserved':True,'service_restart':False}))
'''
    program = 'import re\n' + inspect.getsource(production_flags) + '\n' + code
    result = subprocess.run(['ssh', '-p', str(config['port']), *client.ssh_options(config),
                             f"{config['user']}@{config['host']}", 'python3 - ' + revision],
                            input=program, capture_output=True, text=True)
    if result.returncode:
        print('PHP configuration operation failed; inspect private audit log')
        log=root/'.deploy/audit/config-error.log';log.write_text(result.stderr);log.chmod(0o600)
        raise SystemExit(result.returncode)
    proof=json.loads(result.stdout)
    if proof['changed']:
        path=root/'.deploy/audit/php.env.before'
        client.copy(config,f"{config['deploy_dir']}/audit-config/{revision}/php.env.before",path,download=True)
        path.chmod(0o600)
        import hashlib
        if hashlib.sha256(path.read_bytes()).hexdigest()!=proof['backup_sha256']:
            raise ValueError('Off-server config backup checksum mismatch')
    (root/'.deploy/audit/config-proof.json').write_text(json.dumps(proof,indent=2)+'\n')
    print(json.dumps(proof))


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--production', action='store_true')
    if not parser.parse_args().production:
        raise ValueError('Explicit --production required')
    main()
