<?php

declare(strict_types=1);
require dirname(__DIR__) . '/app/bootstrap.php';
use App\Repositories\AccessControlRepository;

$siteAdmin=(string)($argv[1]??'7124');
try{
 $repo=new AccessControlRepository();
 $schema=$repo->schemaReady();
 $roles=$schema?$repo->listRoles():[];
 $ctx=$schema?$repo->contextForUser($siteAdmin):[];
 $roleCodes=array_map(static function(array $r):string{return (string)($r['role_code']??'');},(array)($ctx['roles']??[]));
 $roleMap=[];foreach($roles as $r){$roleMap[(string)$r['role_code']]=$r;}
 $checks=[
  'schema_ready'=>$schema,
  'site_admin_role_seeded'=>isset($roleMap['SITE_ADMIN']),
  'general_manager_role_seeded'=>isset($roleMap['GENERAL_MANAGER']),
  'site_admin_policy_all'=>(string)($roleMap['SITE_ADMIN']['policy_mode']??'')==='ALL',
  'site_admin_auto_new'=>(int)($roleMap['SITE_ADMIN']['auto_include_new']??0)===1,
  'site_admin_all_branches'=>(int)($roleMap['SITE_ADMIN']['all_branches']??0)===1,
  'general_manager_policy_business'=>(string)($roleMap['GENERAL_MANAGER']['policy_mode']??'')==='ALL_BUSINESS',
  'general_manager_auto_new'=>(int)($roleMap['GENERAL_MANAGER']['auto_include_new']??0)===1,
  'site_admin_user_assigned'=>in_array('SITE_ADMIN',$roleCodes,true),
 ];
 $failed=[];foreach($checks as $k=>$ok){if(!$ok)$failed[]=$k;}
 $result=['schema'=>'DDB_ACCESS_CONTROL_P14_LIVE_ACCEPTANCE','captured_at'=>date(DATE_ATOM),'site_admin'=>$siteAdmin,
  'roles'=>$roles,'checks'=>$checks,'failed'=>$failed,'status'=>$failed===[]?'PASS':'FAIL','oracle_writes'=>'NONE'];
}catch(Throwable $e){$result=['schema'=>'DDB_ACCESS_CONTROL_P14_LIVE_ACCEPTANCE','status'=>'FAIL','failed'=>['live_execution'],'error'=>preg_replace('/\s+/',' ',$e->getMessage()),'oracle_writes'=>'NONE'];}
$dir=dirname(__DIR__).'/storage/evidence/access_control';if(!is_dir($dir))@mkdir($dir,0775,true);
$file=$dir.'/ACCESS_CONTROL_R45_P14_LIVE_ACCEPTANCE_'.date('Ymd_His').'.json';file_put_contents($file,json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES),LOCK_EX);
echo json_encode($result+['evidence_file'=>$file],JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES),PHP_EOL;
exit(($result['status']??'FAIL')==='PASS'?0:1);
