"""One-time, reviewed integration of the PHP 8.3 dependency baseline and accounting patch."""
from pathlib import Path
import json, shutil, subprocess, hashlib

root = Path(__file__).resolve().parents[1]
workspace = root.parents[1]
reference = workspace / '02-Restaurants/Kemet-Restaurants-Console'
def edit(rel, old, new):
    p = root / rel
    s = p.read_text(encoding='utf-8-sig')
    if old not in s:
        assert new in s, (rel, old[:70])
        return
    p.write_text(s.replace(old, new), encoding='utf-8', newline='\n')

for rel in ['composer.json', 'composer.lock', 'config/modules.php']:
    shutil.copy2(reference / rel, root / rel)
shutil.copytree(reference / 'packages/legacy-menus', root / 'packages/legacy-menus', dirs_exist_ok=True)
edit('app/User.php', 'class User extends Authenticatable', 'class User extends Authenticatable implements \\Laravel\\Passport\\Contracts\\OAuthenticatable')
edit('app/Providers/AuthServiceProvider.php', '$this->registerPolicies();', '$this->registerPolicies();\n        \\Laravel\\Passport\\Passport::$clientUuids = false;')
edit('app/Http/Middleware/VerifyCsrfToken.php', 'use Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken as BaseVerifier;', 'use Illuminate\\Foundation\\Http\\Middleware\\PreventRequestForgery as BaseVerifier;')
edit('app/Http/Middleware/VerifyCsrfToken.php', '    protected function inExceptArray($request)', '    protected function hasValidOrigin($request) { return false; }\n\n    protected function inExceptArray($request)')
for line in ['        Unicodeveloper\\Paystack\\PaystackServiceProvider::class,', '        Knox\\Pesapal\\PesapalServiceProvider::class,', "        'Paystack' => Unicodeveloper\\Paystack\\Facades\\Paystack::class,", "        'Pesapal' => Knox\\Pesapal\\Facades\\Pesapal::class,"]:
    p=root/'config/app.php';s=p.read_text(encoding='utf-8-sig');p.write_text(s.replace(line+'\n',''),encoding='utf-8')
modules={p.name: True for p in (root/'Modules').iterdir() if (p/'module.json').exists()}
# Legacy subscription administration is replaced by the isolated platform console.
modules['Superadmin']=True
(root/'modules_statuses.json').write_text(json.dumps(modules,indent=2),encoding='utf-8')
env=(reference/'.env.example').read_text(encoding='utf-8').replace('KEMET Restaurants','KEMET Retail POS').replace('8787','8788').replace('kemet_restaurants_local','kemet_retail_local').replace('console.localhost','console.retail.localhost').replace('PLATFORM_BASE_DOMAIN=localhost','PLATFORM_BASE_DOMAIN=retail.localhost')
(root/'.env.example').write_text(env,encoding='utf-8')
(root/'.gitignore').write_text('/.env\n/vendor/\n/node_modules/\n/runtime/\n/storage/**/*.log\n/public/uploads/\n/bootstrap/cache/*.php\n/storage/framework/\n',encoding='utf-8')

patch = workspace/'00-Inbox/XBRL-Implementation-20260923'
source = workspace/'03-Retail/Kemet-Retail'
manifest=json.loads((patch/'retail-manifest.json').read_text(encoding='utf-8'))
results=[]
for row in manifest['files']:
    rel=row['path']; destination=root/rel; incoming=source/rel; before=patch/'before/retail'/rel
    assert hashlib.sha256(incoming.read_bytes()).hexdigest()==row['after_sha256'],rel
    destination.parent.mkdir(parents=True,exist_ok=True)
    if not destination.exists() or destination.read_bytes()==incoming.read_bytes():
        shutil.copy2(incoming,destination);result='added or current'
    elif before.exists():
        # Keep newer received code and merge only the previously reviewed reporting patch.
        merged=subprocess.run(['git','merge-file','-p',str(destination),str(before),str(incoming)],capture_output=True)
        if merged.returncode==0:
            destination.write_bytes(merged.stdout);result='merged'
        else:
            conflict=root/'runtime/accounting-merge'/rel
            conflict.parent.mkdir(parents=True,exist_ok=True);conflict.write_bytes(merged.stdout)
            result='needs review'
    else: result='needs review'
    results.append({'path':rel,'result':result})
(root/'docs/platform/accounting-integration.json').write_text(json.dumps(results,indent=2),encoding='utf-8')
print(json.dumps(results,indent=2))
