"""Integrate the reviewed shared Console foundation into the independent Retail baseline."""
from pathlib import Path
import shutil,re,json
root=Path(__file__).resolve().parents[1]
ref=root.parents[1]/'02-Restaurants/Kemet-Restaurants-Console'
def read(p):return (root/p).read_text(encoding='utf-8-sig')
def write(p,s):
 (root/p).parent.mkdir(parents=True,exist_ok=True);(root/p).write_text(s,encoding='utf-8')
def change(p,old,new):
 s=read(p)
 if new in s:return
 assert old in s,(p,old[:70]);write(p,s.replace(old,new,1))
for path in [*ref.glob('public/css/platform-*.css'),*ref.glob('public/js/platform-*.js'),*ref.glob('database/migrations/2026_09_27_*.php'),*ref.glob('database/migrations/2026_09_28_*platform*.php')]:
 dest=root/path.relative_to(ref);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dest)
for locale in ['ar','en']:
 for path in (ref/'resources/lang'/locale).glob('platform*.php'):
  for base in ['lang','resources/lang']:
   dest=root/base/locale/path.name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dest)
shutil.copytree(ref/'public/fonts/Almarai',root/'public/fonts/Almarai',dirs_exist_ok=True)
for p in ['config/platform.php','tests/Platform/bootstrap.php']:
 write(p,(ref/p).read_text(encoding='utf-8'))
for p in (ref/'tests/Platform').glob('*.php'):
 if p.name!='bootstrap.php':shutil.copy2(p,root/'tests/Platform'/p.name)
# Copy and adapt the shared labels; Retail UI assets stay byte-for-byte original.
for base in ['app/Platform','resources/views/platform','resources/lang','lang']:
 for path in (root/base).rglob('*.php'):
  if base in ['lang','resources/lang'] and not path.name.startswith('platform'):continue
  s=path.read_text(encoding='utf-8')
  for before,after in [('RESTAURANTS CONSOLE','RETAIL POS CONSOLE'),('KEMET Restaurants','KEMET Retail POS'),('المطاعم','المتاجر'),('مطاعم','متاجر'),('المطعم','المتجر'),('مطعم','متجر'),('Restaurants','Retail businesses'),('restaurants','stores'),('Restaurant','Store'),('restaurant','store')]:
   # Namespace/controller references are adapted explicitly below, never by label substitution.
   if before in ['Restaurant','restaurant'] and base=='app/Platform':continue
   s=s.replace(before,after)
  path.write_text(s,encoding='utf-8')
change('config/platform.php',"'kmet.cloud'","'kmet.io'")
change('config/platform.php',"'console.kmet.cloud'","'console.kmet.io'")
change('config/platform.php',"'res.kemetkw.com'","'pos.kemetkw.com'")
change('config/platform.php',"        'kitchen' => 'المطبخ',\n        'tables' => 'الطاولات',", "        'add_sale' => 'المبيعات',\n        'stocktaking' => 'الجرد',\n        'exchange' => 'استبدال المنتجات',")
change('config/app.php','App\\Providers\\AppServiceProvider::class,','App\\Providers\\AppServiceProvider::class,\n        App\\Platform\\PlatformServiceProvider::class,')
change('app/Http/Kernel.php','\\App\\Http\\Middleware\\TrustProxies::class,','\\App\\Http\\Middleware\\TrustProxies::class,\n        \\App\\Platform\\Http\\ResolveHost::class,')
change('app/Http/Kernel.php','\\App\\Http\\Middleware\\VerifyCsrfToken::class,','\\App\\Platform\\Http\\ConsoleLocale::class,\n            \\App\\Http\\Middleware\\VerifyCsrfToken::class,\n            \\App\\Platform\\Http\\SurfaceAccess::class,\n            \\App\\Platform\\Http\\TenantResources::class,')
change('app/Http/Kernel.php',"'api' => [","'api' => [\n            \\App\\Platform\\Http\\SurfaceAccess::class,\n            \\App\\Platform\\Http\\TenantResources::class,")
priority=(ref/'app/Http/Kernel.php').read_text(encoding='utf-8').split('    protected $middlewarePriority = [',1)[1].split('    ];',1)[0]
priority=priority.replace('        \\Illuminate\\Foundation\\Http\\Middleware\\HandlePrecognitiveRequests::class,\n','')
change('app/Http/Kernel.php','class Kernel extends HttpKernel\n{','class Kernel extends HttpKernel\n{\n    protected $middlewarePriority = ['+priority+'    ];\n')
change('app/Providers/RouteServiceProvider.php',"->group(base_path('routes/web.php'));","->group(base_path('routes/web.php'));\n\n            if (config('platform.enabled')) require base_path('routes/platform.php');")
change('app/Http/Middleware/VerifyCsrfToken.php','class VerifyCsrfToken extends BaseVerifier\n{',"""class VerifyCsrfToken extends BaseVerifier
{
    protected function inExceptArray($request)
    {
        if (config('platform.enabled') && $request->getHost() === config('platform.console_host')) return false;
        return parent::inExceptArray($request);
    }
""")
for path in ['app/Http/Controllers/Auth/ForgotPasswordController.php','app/Http/Controllers/Auth/ResetPasswordController.php']:
 source=(ref/path).read_text(encoding='utf-8');method=source.split('    protected function credentials(',1)[1].split('\n    }',1)[0]
 s=read(path);marker='    use '+('SendsPasswordResetEmails;' if 'Forgot' in path else 'ResetsPasswords;')
 change(path,marker,marker+'\n\n    protected function credentials('+method+'\n    }\n')
credentials=(ref/'app/Http/Controllers/Auth/LoginController.php').read_text(encoding='utf-8').split('    protected function credentials(',1)[1].split('\n    }',1)[0]
change('app/Http/Controllers/Auth/LoginController.php','    public function logout()', '    protected function credentials('+credentials+'\n    }\n\n    public function logout()')
hook=(ref/'app/Exceptions/Handler.php').read_text(encoding='utf-8').split('        $this->reportable(',1)[1].split('\n        });',1)[0]
s=read('app/Exceptions/Handler.php');s=re.sub(r'        \$this->reportable\(.*?\n        \}\);',lambda _: '        $this->reportable('+hook+'\n        });',s,flags=re.S);write('app/Exceptions/Handler.php',s)
change('app/Utils/ModuleUtil.php','public function hasThePermissionInSubscription($business_id, $permission, $callback_function = null)\n    {',"""public function hasThePermissionInSubscription($business_id, $permission, $callback_function = null)
    {
        if (config('platform.enabled') && array_key_exists($permission, config('platform.modules', []))) {
            return app(\\App\\Platform\\Entitlements::class)->allows((int) $business_id, $permission);
        }
""")
change('Modules/Superadmin/Entities/Subscription.php','public static function active_subscription($business_id)\n    {',"""public static function active_subscription($business_id)
    {
        if(config('platform.enabled')){
            $row=app(\\App\\Platform\\Subscriptions::class)->current((int)$business_id);
            return $row?static::find($row->id):null;
        }
""")
for name in ['Account','Brands','Contact','BusinessLocation','Category','Product','User','Unit','TaxRate','Transaction']:
 p='app/'+name+'.php';s=read(p)
 s,n=re.subn(r'(class '+name+r'\b[^\n]*\n\{)',r'\1\n    use \\App\\Platform\\ScopedTenantResource;',s,count=1);assert n,p;write(p,s)
for name in ['VariationLocationDetails','PurchaseLine','Variation','ProductVariation','StockAdjustmentLine','TransactionSellLine']:
 p='app/'+name+'.php';s=read(p)
 s,n=re.subn(r'(class '+name+r'\b[^\n]*\n\{)',r'\1\n    use \\App\\Platform\\ScopedTenantChild;',s,count=1);assert n,p;write(p,s)
schedule=(ref/'app/Console/Kernel.php').read_text(encoding='utf-8').split("        if (config('platform.enabled')) {",1)[1].split("        $env",1)[0]
change('app/Console/Kernel.php','protected function schedule(Schedule $schedule)\n    {',"protected function schedule(Schedule $schedule)\n    {\n        if (config('platform.enabled')) {"+schedule)
change('app/Platform/Http/ResolveHost.php',"'kemet_console_session' : 'kemet_restaurant_session'","'kemet_retail_console_session' : 'kemet_retail_session'")
# Console layout shares functionality, not the Restaurant product skin.
change('resources/views/platform/layout.blade.php',"@include('platform.ui.favicon')",'<link rel="stylesheet" href="/css/platform-retail.css?v=retail-rc1">'+"@include('platform.ui.favicon')")
for p in ['resources/views/platform/login.blade.php','resources/views/platform/access.blade.php']:
 if (root/p).exists() and "@include('platform.ui.favicon')" in read(p):change(p,"@include('platform.ui.favicon')",'<link rel="stylesheet" href="/css/platform-retail.css?v=retail-rc1">'+"@include('platform.ui.favicon')")
write('resources/views/platform/ui/brand.blade.php','<span class="kemet-brand" dir="ltr"><img src="/img/kemet-icon.png" alt="KEMET Retail POS" width="52" height="52"><span class="kemet-brand-type" aria-hidden="true">KEMET<small>RETAIL POS CONSOLE</small></span></span>\n')
write('resources/views/platform/ui/favicon.blade.php','<link rel="icon" type="image/png" href="/favicon.png"><link rel="shortcut icon" href="/favicon.ico"><link rel="apple-touch-icon" href="/apple-touch-icon.png"><meta name="theme-color" content="#004eeb">\n')
print('Shared platform integrated. Retail-specific storefront, order and schema adapters must pass verification before release.')
